Learn about Variables in Javascript

If you have done any programming you will be at home with variables. If you haven’t then don’t worry it’s quite easy to understand.

Variables are used to store values. Value can be a string, a number or other forms of data.

Code - https://github.com/ankur-srivastava/javascript-lectures/blob/master/Lecture2/index.js

Let’s understand this with an example. You may have seen websites that ask you to enter your first name etc. Now to store that name we need a variable.

let firstName = 'Ankur';

Here firstName is a container that stores Ankur.

Declare a Variable
To use variables you need to declare them. We use keywords like let, var or const to declare variables. const is used to declare variables whose values do not change.

let age = 30;
const color = 'red';

What happens if you just write

let day;

It gives undefined, since we dint assign any value.

Initialize a Variable
Initialize means assigning a value to a variable.

let day = 'Tuesday';

Why you should use let instead of var ?

With var you can declare a variable after initializing. This is known as hoisting. And is not good. You cannot do the same thing with let.
Another thing that works with var and not let is that with var you can declare a variable multiple times.

var fName = 'Ankur';
var fName = 'Sid';

For these reasons it’s not advisable to use var.

A variable declared using let or var can be updated.

let name = 'Jack';
name = 'Sid';

Variable Naming Rules

1. Don’t use numbers at the start of variables. This is not allowed.
2. Variable names are case sensitive.
3. Using camelCase is safe and recommended.
4. Variable names should be intuitive.
5. Don’t use the reserved words. That is words that are part of JS syntax. Like let, const, function etc.

Variable Types

You don’t need to specify variable types in JS. It’s a dynamically typed language, quite similar to Python. In other languages like C or Java you may have seen various data types being used like int, long, boolean, float etc. Not needed with JS.

You can store numbers, strings, booleans, arrays and objects.

Let’s see some examples:

let message = 'Hello all';
let age=32;
let flag = false;
let a = [10, 12, 32]

Author: codesmartly


Leave a Reply


WordPress.com Logo


Google photo


Twitter picture


Facebook photo


Connecting to %s