Tutorials

Minimal Introduction to JavaScript variables

Sending
User Rating 5 (1 vote)

JavaScriptJavaScript variables are used to hold values or expressions. A variable name can be as short like  x, or a more descriptive name, like carname.  Declaring variables is an integral part of any programming language. Developers declare variables to reserve address space in the computer's memory so that they can use it further as in fucntion or anywhere down the program. Variable can be Global or lexical. Always remember not to declare the same variable name at global place and if its being used by only one fucntion or only at one place declare it inside that block only.

 

Rules for JavaScript variable names and declaration:

  • Variable names are case sensitive (y and Y are two different variables). It should be followed throughout the code to avoid declaring two different variables with different cases. This also avoids syntax errors when running the code in the user's browser.
  • Always use  camel casing while declaring variable. ex: var alienCoders = "https://www.aliencoders.org"
  • Variable names must begin with a letter or the underscore character. ex: 123goAhead is wron
  • JavaScript variable can be created or declared by using reserved keyword "var". ex: var x=100; var carName="Mercedes Benz";
  • If you redeclare a JavaScript variable, it will not lose its original value unless and until you changed its value. var x=5; var x; After execution of these statements value of x will be still 5 only.
  • JavaScript is smart enough to understand the data type of variable just by its declared value. Ex: var x=5; (datatype is int) var y = "Me"; (string)
  • = is used for assignment and + is used for addition of two numbers or two strings. ex: var x=5; var y = 2+5 ; (o/p will be y =7) var place = "New "+"Delhi"; (o/p will be "New Delhi")

We will post about operators and data types very soon!

Share your Thoughts