I am now beginning my JavaScript path and have a question on usage of variables in Console.log
How can this code give me an error?
var myAns = console.log(65/240);
console.log(100* +Number(myAns) );
If I am assigning output of the Console.log to the variable 'myAns' cannot I use that as a reference in another Console.log?
I searched elsewhere and saw that I needed to use another +operator right in front of the value (didnt work) or that I needed to input the Number() method in place (didnt work)
And the error I am getting is just: NaN
I believe I am Passing by reference, or is that the scope problem?
If I am assigning output of the Console.log to the variable 'myAns' cannot I use that as a reference in another Console.log?
In order to do this you would need to override the default console.log() function. Another, easier approach would be to do:
console.log(myAns = 65/240)
As in, console.log the result of assigning 65/240 to myAns.
Right now, you're doing var myAns = console.log(65/240); which, as Bergi mentioned, assigns the return value of console.log(65/240) (undefined) to myAns.
You are assigning return value of "console.log" to myAns. It doesn't return the result of the calculation. What you need is:
var myAns = 65/240;
console.log(myAns);
var myOtherAnswer = 100 * myAns;
console.log(myOtherAnswer);
IF a specific function has a return statement with a return value, then it will return that value once that function is being invoked from somewhere..
console.log just logs (displays) the value passed inside the parenthesis of the console.log(....) to the browser.
console.log() doesn't assigns a value back to a variable...
var value = console.log(100);
here it just displays the 100 on the browser but nothing will be assigned to value variable..
Related
After I create an object of primitive type on javascript console, it return undefine
for example
var john = new String("John");
undefined
But after continue to type
john
String {'John'}
When typing code into the console, what it "reads back" to you after you press enter is the completion value of the last statement.
Variable declarations do not result in any completion value, so it reads back to you undefined.
But, a statement referencing an existing identifier will give you the value in the identifier - which, in this case, is a String object.
(But, keep in mind that there's almost no good reason to use the primitive constructors - better to use var john = 'John';)
When you declare a variable and assign a value to it in console, it just sets the variable to the value you assigned it, it doesn't return anything.
So, if you open dev tools console and type:
let a = 1;
console will report undefined
if you then type a into console and press return, 1 will be displayed as the value returned by variable name a.
What you described is normal behaviour for the console.
I'm still new to Javascript so please forgive me if this seems like a silly question.
I defined a function called randomNumberGenerator, and in it is just one line of code. Basically, the purpose of it is to return a number between 0 and 2.
function randomNumberGenerator() {
return Math.round(Math.random() * 2);
};
However, when I tried to log the result of this function in my console, it shows me the outline (is that what it's called) of that function instead of a random number. You can see it here:
ƒ randomQuestionSelector() {
return Math.round(Math.random() * 2);
}
I tried assigning 'Math.round(Math.random() * 2)' to a simple variable, and logging that variable to the console. It worked as expected (I got a random number), so I'm confused why doing the same with a function doesn't.
Hope someone can help me out with this. Thank you!
The reason why console.log(randomNumberGenerator) returned such a value is that you did not really invoke this function. You called the default .toString() method which exists on every object. And default implementation (which can be overriden) returns what you saw in the console. If you want to get the result of the function you need to use () operator which calls the function, like this:
randomNumberGenerator()
And to capture the returned value you can assign it to the variable, for example:
const random = randomNumberGenerator()
console.log(random);
That way you are calling the function and assigning the returned value to the new variable.
You need to call the method. What you are likely doing is calling console.log(randomNumberGenerator) rather than console.log(randomNumberGenerator())
can some please explain why this function returns its original argument value instead of the altered value.
edit: FYI I know the solution to the problem already i just don't understand what is going on 'under the hood'; what is causing this not to work. i want better understanding of the language
function helper(value){
let hold = value;
hold.replace(/[^\w]/g, '')
hold.split('')
hold.sort()
hold.join('')
hold.toLowerCase()
return hold
}
console.log(helper('hello world')) <--- returns 'hello world'
You need to reassign, the functions does not change the original value and needs to be re-assigned. You can also use dot operator to combine all the operations and shorten the code like following
function helper(value){
return value.replace(/[^\w]/g, '').split('').sort().join('').toLowerCase();
}
console.log(helper('hello world'))
Alternatively, you can correct your code like this
function helper(value){
let hold = value;
hold = hold.replace(/[^\w]/g, ''); // re-assign
hold = hold.split(''); // re-assign
hold.sort(); // sort updates hold - re-assignment not required
hold = hold.join(''); // re-assign
hold = hold.toLowerCase(); // re-assign
return hold;
}
console.log(helper('hello world'))
replace doesn't modify input argument but returns a new string instead.
I have found the solution as to "WHY" the code was acting the way it was.
it is because Arrays and Objects are mutable, while strings and numbers and other primitives are immutable.
for more info read this blog What are immutable and mutable data structures?
and the solution was posted here by "Nikhil Aggarwal"
Is there way to create a new global method where I can have variable.myMethod() and it return true or false? Basically, I want to check to see if the variable is undefined and instead of using typeof(variable) == 'undefined' or specifying a function, is it possible to do something like variable.isUndefined() and it would return true or false?
I'm going to go ahead and post this as an answer, so I can go into a bit more detail.
As I mentioned in my comment, you have to be extremely careful about the terms that you use here, as undeclared and undefined mean two very different things.
If a variable is "undeclared", it doesn't exist, thus you cannot attempt to call any methods that might exist on it if it were declared.
If a variable is "undefined", it exists, but it doesn't have a value assigned to it. When this is the case, you can attempt to call methods that may exist on it, however the chances are that they'll fail, since variable doesn't have any value.
Every type in JavaScript is a child of the Object type, therefore you add a method to them, like follows:
Object.prototype.myMethod = function() {
console.log("This is my method");
};
So, in theory, you could create a method to check to see if a value exists, and return a true/false value.
Similarly to what StackOverflow user Barmar pointed out, undefined and null are not children of the Object type, thus your method will not exist.
As other comments have stated, you're probably better of sticking with something like follows:
if (!myVariable) {
// myVariable doesn't have a value
}
I'd like to point out that most of my explanation was unnecessary, as user Barmar pointed out, there is no practical difference between undeclared and undefined.
If a variable is undeclared, it's "value" is essentially read as undefined, thus your method will not exist.
this is a paradox. you can never have a method inside an undefined object because and undefined object does not have anything at all. to make it clear imagine this object
var a = {};
a.b is undefined here, so trying to call a.b.isDefined() can not work because you dont even have b. to make it work you need b defined like this
var a = {b:1,isUndefined:function(){return false}}
so you have to make a generic function that takes objects. This will do the trick
function isUndefined(obj,stringLink){
var arrayLink = stringLink.split(".");
var current = obj[arrayLink[0]];
if(!current)return false;
for(var i =1;i< arrayLink.length;i++){
current = current[arrayLink[i]];
if (!current)return false;
}
return true;
}
it will more or less check for nested object until it reach the target.
if you have
var a = {b:{c:{d:{e:{f:1}}}}}
//this function will do a["b"]["c"]["d"]["e"]["f"]
isUndefined(a,"a.b.c.d.e.f") //gives true
//or you can use
if(a&&a.b&&a.b.c&&a.b.c.d&&a.b.c.d.e&&a.b.c.d.e.f)//lots of work here
I am very new to JS.
I ran into something strange, while learning about console.log behavior. Console is very important for me, because I believe that if console.log does not see it, then it is not there. I will start with simple things, just to make sure I do not miss anything.
Assumption: console.log can print results of simple calculations.
console.log(1+0); //1. Console.log can calculate!
Assumption: console.log can print results of functions, if those return values.
var test = function(a,b){
var c = a+b;
return c;
};
console.log(test); //prints the assigned value of the variable "test", which happens to be a function and thus function code is printed. Function is NOT called here.
console.log(test()); //prints NaN, since the function is called but no arguments are provided. Thus, JS is unable to calculate the result.
console.log(test(1,1)); // this one prints the result of the function, which is variable "c"
console.log(test(1,1) + 2); //I can then manipulate results further in the console.
Assumption: with closures there is a problem?
var testClosure = function(a,b){
var c = a+b;
return function(){
var d = c + 1;
return d;
}
};
console.log(testClosure); //so far standard behavior - console prints the assigned value of a function - its code.
console.log(testClosure()); //trying to call the function here without arguments. Expected result that it will attempt to calculate "d" and return NaN (since it cannot calculate), but it returns the code for the anonymous function. JS does not attempt to do calculation.
console.log(testClosure(1,2)); //does not produce the expected result of 4. It produces same output as in the previous case. JS does not attempt to do calculation for some reason.
var result = testClosure(1,2);// Do I understand it correctly that at this point I only create a reference but testClosure() function is not actually launched? Therefore, variable "result" does not have any meaningful value yet?
console.log(result); //printing the assigned value of this variable, which is the code for the anonimous function in testClosure().
console.log(result()); // here I am actually calling the testClosure() function by proxy and get the desired result of 4.
My main questions are
Why does
console.log(test(1,1));
work and
console.log(testClosure(1,2));
does not?
Why does
console.log(testClosure(1,2));
does not work but
var result = testClosure(1,2);
console.log(result());
does work.
I seem to be doing essentually the same thing: calculate given the provided argument and print the result.
Where is the key difference I am missing, since I obviously do?
test is a function, which returns a value, but testClosure is a function which returns a function which returns a value. Function in JS is a first class object, which means that it also can be used as an argument, assigned to a variable or returned from a function (that's what you do in your closure example, you return a function, not the value). But to get a value of this returned function you have to call it too, it does not call itself.
console.log( typeof test(1,2) ); // number
console.log( typeof testClosure(1,2) ); // function, which also needs to be called
console.log( typeof testClosure(1,2)() ); // number
// ---------------------------------^-----// call the returned function
1) because you are logging the result of executing the function, which returns the expected value.
2) because you are logging the result, which in this case is a function, you need to then execute this function to get the desired value - try doing console.log(testClosure(1, 2)());