
Variables in JavaScript: Declaration, Initialization, and Scope
☰Fullscreen
Table of Content:
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
- Variables are the identifiers to store data values in our code.
var
is the keyword to declare a variable.‘=’
is the operator to assign a value to a variable.- A variable must start with
_
or$
orletter
. 99temp is invalid whereas _99temp is valid. - In ES2015(known as ECMAscript), two other ways to declare variables were introduced- let and const. We can use these 2 keywords to define variables(now recommended).
Correct JavaScript variables
var x = 10; var _value="hello";
Incorrect JavaScript variables
var 123=310; var *bb=340;
In later chapter we will discuss about local and global variable.
Solve these below questions.
Sample Question 1:
- Declare two variables with values such as "Tom", "Jerry".
- Concatenate these strings.
- Print the result in a way that the output is "Tom and Jerry".
Sample Question 2:
- Assigning two strings with values "This is", "JavaScript".
- Concatenate these strings.
- Find out the length of the resultant string using ".length".
Sample Question 3:
Print the date as 01-Jan-2016 when
- var year = 2016
- var month = Jan
- var date = 1
Sample Question 4:
Write JavaScript program to convert ?C (Celsius) to ?F (Fahrenheit). You can prompt the user for input ?C using window.prompt
. Formula for converting ?C to ?F is
F = (9 * C/5) + 32
No Questions Data Available.
No Program Data.