Let’s see how to comment in JavaScript first, there are two types of comments:
- Single line comment
// Variable naming rules
- Multi-line comments
/*
lorem
ipsm
*/
Variable Mutation
var firstName = 'John';
var age = 28;
console.log(firstName + ' ' + age);
//John 28
So how does this work as age is a number while firstName is a string ?
This works thanks to type coercion where JS automatically converts data type from one to another when that is needed.
Thus the age here is converted to a string.
Space is also a string, so they can be joined to form a string overall.
Define variables on the same line and assign later on.
var job, isMarried; //we declare and they are both undefined right now.
job = 'teacher'; //Assign value to variable
isMarried = false;
var firstName = 'John';
var job = 'teacher';
var age = 28;
var isMarried = false;
console.log(firstName + ' is a ' + age + ' year old boy and he is a ' + job + '.' + 'Is he married? ' + isMarried);
//John is a 28 year old boy and he is a teacher.Is he married? false
So even boolean got converted to a string.
If we comment our var isMarried = false, the result will be John is a 28 year old boy and he is a teacher. Is he married? undefined
Consequently, undefined is converted into a string.
==> This is so-called type coercion.
Variable Mutation
Variable mutation simply means changing value of a variable.
When we want to change it, var keyword is no longer needed.
var age = 28;
age = 'twenty-eight';
No need to use var to declare it again as it is already declared earlier in the code. JavaScript will figure out its data type and change it on the fly owing to its dynamic typing feature.
//Before it’s a number now it’s a string.
Prompt
We can use prompt to ask a question which the answer for the question can be stored in a variable.
var lastName = prompt('What\'s your last name?');
console.log(lastName);
Please note that this is my study notes that I took while taking the complete guide to JavaScript course on Udemy, if you are interested in understanding the language better, I highly recommend you to purchase the course 🙂 !