JavaScript Variables and Decleration... Knowing the basics
Today, I will be talking about Javascript variables. I got a comment on my last post and I think I need to explain variables to the commenter. So, we will be talking about Variables and declaration.
The keywords to define a variable is var, let and const. var has been around since the beginning of JS. let and const were introduced in ES2015 also known as ES6. var has been what many people use, but in the modern JavaScript, let and const are better as all browser can read it.
This is the basic, when you use var and let to assign a variable, you can reassign it and you will not get an error. For instance,
var name = 'vidder';
console.log(name);
name = 'power';
console.log(name);
// If you open your browser console you will see both names logged
// Initializing variables
var food;
console.log(food);
food = 'Pizza';
console.log(food);
// The first will log Undefined as we did not define the variable and the second will log Pizza.
// A variable can only include letters, numbers, _,$ and cannot start with a number else you will get a SyntaxError.
// Multiple words variables declaration
var sweetFruit = 'Mango'; // Camel Casing
var sweet_fruit = 'Orange'; // Underscore
var SweetFruit = 'Guava'; // Pacal Casing
// I will recommend Camel case for you to use when declaring multiple words.
// We can do the same thing with the let keyword. It is identical on the global scope, but with little differences in block level, but const work differently. const stands for constant and simply means that it can't change.
// const
const sport = 'Soccer';
console.log(sport);
// That would work, but what we can't reassign
sport = 'Basketball';
// It will throw up TypeErr. Also, when using const, you have to assign a value. Unlike we did with var or let.
const sport;
// This will throw up an err. We can use const in an array and object literals and it won't throw an error because we will mutate the data, not the variable.
Object
const footballer = {
name: 'Ronaldo',
age: 35,
wing: 'Forward'
}
footballer.name = 'Messi';
footballer.age = 33;
console.log(footballer);
// This will log Messi, 33 and Forward.
These are the basics you need to know about variables and declarations. I planned to start from the very genesis, but the comment made me explain this. I hope people find it useful.
Thank you!
Hello vidder!
Congratulations! This post has been randomly Resteemed! For a chance to get more of your content resteemed join the Steem Engine Team
I am a starter coder. I would like to see something html and css.