Code from task 22 - variables


#1

I'm a little confused with the code required to declare a variable all the instructions and examples suggest the following layout:

var myName = "leng";
var myAge = 30
etc...

But the defualt code in the exercise window reads:
// To create a variable, we use only one equals sign
// But to check if two values are equal, we use 3 equal signs.
// declare your variable here:
console.log(myAge);

now should my exercise answer be:

console.log(myAge = 31);
or
var myAge=31;

I'm thrown and confused by the appearance of console.log?

Any thoughts cheers Andrew


#2

Your answer should be:

var myAge=31;

this declares a variable. Console.log only log things to the console (the output window on the right side), now you could use console.log to log your variable to the console:

console.log(myAge);

now you should see 31 on the screen


#3

Thank you Stetim94 for your quick reply

So just to clarify:

console.log(myAge = 31); post the output i.e. 31 to the output window but would not declare the result and so would not be available to call back at a later stage.

where as

var myAge=31; would declare the variable and effectively save the value 31 against the case-sensitive name. If i was to ever type myAge again it would then return the value 31. but this operation of saving the variable would not be visible to the output window ?

is it possible then or sensible to be able to both save the variable using var and log the opertation to the console?

maybe?:
var myAge=31;
console.log(myAge = 31);

Cheers Andrew


#4

this:

console.log(myAge = 31);

is very bad, you can't declare a variable inside console.log. If you want to this, you need to declare a variable first, and the print its value to the console:

var myAge = 31;

now your myAge variable has a value of 31, so now you can log the variable the console:

console.log(myAge);

which also answers your last question, once you saved your variable, you can just print it to the console.


#5

Thanks again Stetim94

Crystal clear...Got it!

  1. Define your variable : var myAge=31;
  2. Once defined substitute in the variable name (in this case myAge) in to code lines to display or use the value
    2a. example of use: console.log(myAge); would display 31 in console
    2b. example of use: if(myAge === 31) { console.log("This is my age");} else{ console.log("This is not my age");}

Cheers again

Andrew


#6

You got the hang of it :slightly_smiling: