Variables in JavaScript: Declaration, Initialization, and Scope

Rumman Ansari   Software Engineer   2024-07-09 09:40:10   8780  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

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 $ or letter. 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

<span class="pln">
</span><span class="kwd">var</span><span class="pln"> x </span><span class="pun">=</span><span class="pln"> </span><span class="lit">10</span><span class="pun">;</span><span class="pln">  
</span><span class="kwd">var</span><span class="pln"> _value</span><span class="pun">=</span><span class="str">"hello"</span><span class="pun">;</span><span class="pln">  
</span>

Incorrect JavaScript variables

<span class="pln">
</span><span class="kwd">var</span><span class="pln">  </span><span class="lit">123</span><span class="pun">=</span><span class="lit">310</span><span class="pun">;</span><span class="pln">  
</span><span class="kwd">var</span><span class="pln"> </span><span class="pun">*</span><span class="pln">bb</span><span class="pun">=</span><span class="lit">340</span><span class="pun">;</span><span class="pln">  
</span>

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.

Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.