What are the values that can be assigned to variables in javascript? - javascript

In all programming languages "variables" can be defined as follows :
"They are reserved places in RAM to store data"
Turns out that such code is logical in javascript:
var x = document.getElementById("IdName");
x.innerHTML = "Hello Stack Overflow";
Or This Code:
var x = alert("Hello Stack Overflow");
I don't get it, Of course alert() and document.getElementById("")
aren't data to be assigned to variables
I want someone to explain why such thing is possible.
I'm really confused of this.

No, document.getElementById("IdName") "isn't" data; it's a function call that returns data:
Returns a reference to the element by its ID [...]
Syntax
element = document.getElementById(id);
Parameters
id
is a case-sensitive string representing the unique ID of the
element being sought.
Return Value
element
is a reference to an Element object, or null if an element with the
specified ID is not in the document.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
The function call returns an object of type Element (or null), which is data a value that can be assigned to a variable. This works pretty much exactly the same in virtually all programming languages. Values can be assigned to variables. Functions return values.
alert() does not happen to return anything, which means it implicitly returns undefined, so the value undefined will be assigned to x. That is a rather useless operation, but still works by the same rules.

Related

Can someone please explain in plain english what is going on in a particular part of my code for objects?

although it is a very simple code, I would like to get a full understanding of what is happening in my condition:
let getFreqOn = function(string){
//set a variable for object
let object = {}
for (let key = 0; key < string.length; key++){
// if (object.hasOwnProperty(string[key])) {
// if (object[string[key]]) {
// if (object[string[key]] !== undefined) {
if (string[key] in object) {
object[string[key]]++
}
else{
object[string[key]] = 1
}
}
return object
}
My main concern would be the first condition, I understand what it is they do but I cant put in to plain English how it is working. For example if (string[key] in object) is basically telling my that if a specific property is in the empty object I defined, then I will set then it will be set as the property and incremented. But what I'm trying to wrap my head around is that the object is empty, so how can the property be in the object?
Hoping someone can enlighten me on the conditions that I commented out as well. Sorry for the noob question.
First, the in operator returns a boolean result. It checks whether the string on the left is present as a property name in the object on the right.
Thus
if (string[key] in object)
asks whether that single character of the string is in use as a property name in the object. As you observed, the very first time through the loop that cannot possibly be true, because the object starts off empty.
Thus the if test is false, so the else part runs. There, the code still refers to object[string[key]], but it's a simple assignment. An assignment to an object property works whether or not the property name is already there; when it isn't, a new object property is implicitly created.
The key difference is right there in the two different statements from the two parts of the if - else:
object[string[key]]++; // only works when property exists
object[string[key]] = 1; // works always

How know variable name in javascript?

Suposse an function:
function get(){}
this will get an variable
var name = "Eduardo";
get(name);
function get(n) {}
And i want to show the name of the variable that was passed, without know this name.
function get(n) {
return getNameVariableFromValue(n); // Pseudocode for explain my question
}
so, i want the name of variable without previouslu knowing this name.
PD: My question is mainly to know, who is a variable in the window object, without know this name or value
Your question assumes that no two properties would ever have the same value, which is highly unlikely. But, making that wild assumption, you'd need to make the new window property explicitly rather than just declare a global variable and then you could use Object.keys() to enumerate all the key names of the window object, looking for the one that matches your value. When found, report the key name.
window.myGlobal = "Test";
Object.keys(window).forEach(function(key){
if(window[key] === "Test"){
console.log(key);
}
});
This code won't work in the Stack Overflow snippet environment due to sandboxing, but you can see it working here (make sure to have your developer's tools console open when running).
You can send the value as an object to the function and do something like below
function get(n) {
return Object.keys(n)[0];
}
var name ="Test1";
var name2 = "Test2"
console.log(get({name}))
console.log(get({name2}))

Setting Variable Assignments with property display

I'm still a novice when it comes to JavaScript and was trying to make my code more cleaner and was wondering why the top scenario works but the bottom doesn't? Am I missing something?
var partner = document.getElementById('partner');
var providedBy = document.getElementById('providedBy');
partner.style.display = "none";
providedBy.style.display = "none";
But this does not?
var partner = document.getElementById('partner');
var providedBy = document.getElementById('providedBy');
collection = partner + providedBy;
collection.style.display = "none";
In the console it gives me error saying Cannot set Property 'display' of undefined. Am I supposed to define it somewhere first? I console logged the new variable and it returned both div elements.
collection is of type string as the + operator automatically call for both their toString() function.
Now what you are trying is to access a property of collection.style which does not exist because you are operating on a string. That's the reason for the error message you are getting.
You could do something like:
var collection = [];
collection.push(document.getElementById('partner'));
collection.push(document.getElementById('providedBy'));
collection.forEach(function(element) {
element.style.display = 'none';
}
which would be something I think you are trying to archive.
just to complement the accepted answer, I think you should understand why you get this error.
For what i understand from your code, you are trying to set the css of both variables partner and providedBy to display : none.
Your first piece of code works because you do this separately, while in your second code you try to add with the (+) operator both nodes, which evaluates to the string "[object HTMLDivElement][object HTMLInputElement]".
Then you try to call .style on that string which evaluates to undefined, and then you try to call display on that undefined value, this is where you get the error.
You could leave your code just like that since there are not too many variables, but if you wanted to do something that worked on multiple variables you could
create an array
push your objects into the array
create a function that loops over the elements of the array and set their style.display = "none" to individually.
In JavaScript you have to declare all of your variables. Secondly, you can't point to two objects at once by using the + operator. JavaScript interprets this as trying to concatenate the two objects, which it can't do in this way. It will return the string [object Object][object Object]
In order to affect two Objects at the same time you would need to create a function or use an existing method.

name already defined in console!?

Could anyone explain why this code returns
""
in firebug console?
Don't down-vote thinking it's just a typo! :O
I was curious to know why it doesn't throw an error!!!
function mds() {
var {
namex,
score,
className
}
= {
namex: 'NAME',
score: '10',
className: 'Oop'
};
this.test = function () {
return name;
};
}
var x = new mds();
x.test()
I would also love to hear more details on this type of variable mapping (or a link) ?
UPDATE:
I would like to know why name is predefined with value "" in console?
The JavaScript part of the explanation here is simple.
When you do this:
this.test = function () {
return name;
};
It will first look for a variable named name in the scope of the function this.test(). When name is not found there, it will check in the parent function's scope as well. And since name is not defined there as well, it will look in the global scope, which is window, and returns the value of window.name, which in this case is an empty string. This (window.name) is what you are seeing when you run name in the console (or Firebug). This much is simple.
The value of window.name is decided according to it's definition in the HTML Standard (not according to ECMAScript rules). This MDN page says:
window.name - Gets/sets the name of the window.
And in your case, the name of the window is empty, hence the empty string you are getting. That's the simpler explanation of why window.name is empty.
If you really want to understand why window.name is empty here, you need to check out the HTML Specification for what it says about browsing contexts. It says that the value of window.name will be the name of the current browsing context.
A browsing context is an environment in which Document objects are presented to the user. (from the spec)
For example, when you create a link in HTML using the below code, the target attribute specifies the target browsing context in which the page is to be opened.
Click me
See more examples in this JSBin.
Hope this was somewhat helpful. Read the HTML Spec to understand more about browsing contexts.
Even if you run the below code you get "".
function ha() {
return name;
}
ha();
returning of "" has no way related to
var {
namex,
score,
className
}
= {
namex: 'NAME',
score: '10',
className: 'Oop'
};
Another way to test it is, Just type 'name' press enter in console.
""
Updating as per "Krishna" observation.
Looks like name is predefined in console context. So if the user doesnt have another declaration of name within the scope the console returns an empty string "". If user has declared name="xyz" then xyz is returned
name is a legitimate window property.
Windows can have names. And they can be useful.
As in:
Open a new window, with the name of namedWindow!
...and to make this more informal, we should add that: a link with a named target will either open in an existing window with that name or will create a new one with the given name in case it's not.
And because the "name" token is a global property of the window context; stating: name in the console or anywhere in the script will of course return an empty value (of a proper/accepted type), that is: a string. In this case [meaning the window.name hasn't been defined yet] an empty ("") string, is the only correct value for that property.
Whereas an unset event of a window, or any DOM element - if it exists - should return null, not undefined or god forbid an empty string, because they (event properties) expect functions; and functions are of type object, and null represents an empty object.
However, an unset, inline event attribute of an html element - should return an empty string ("").
Try this,
var {
namex: name,
score: score,
className
} = {
namex: 'NAME',
score: '10',
className: 'Oop'
};
actually object have to be key value pair

What does this mean?

function fkey(a) {
a || (a = {});
if (!a.fkey) a.fkey = $("input[name='fkey']").attr("value");
return a
}
I guess a is actually a function, but how to understand (!a.fkey) ?
a is an object in this case, it's setting the .fkey property on it if it isn't set (or is falsy) already.
For SO chat, this allows the fkey input to either be provided or gotten from the page, it's a hidden input at the bottom of your page, populated with a value used to authenticate your request and such.
Currently it's always pulling from the DOM, so really this function just adds the property, it would leave it alone if it were provided though.
a is not a function, it's an object.
The a.fkey is accessing a member of the a object. The ! in front means that if the member does not exist or the value is falsy, the expression evaluates to true and the fkey member is set to $("input[name='fkey']").attr('value');, which can also be accomplished with .val() instead of .attr('value')
The function you posted adds a member named fkey to a if it did not already exist. The !a.fkey part essentially means "does not already exist" (this works because once assigned, the member does not evaluate to false).
The function takes an object and adds an fkey property to it, which will be the value of
<input name="fkey"> field.
For example:
<input name="fkey" value="WATCH ME HERE">
var temp = {}; // make a new object
fkey(temp); // expand it with fkey's value
alert(temp.fkey); // WATCH ME HERE

Categories