× Introduction Setup Environment Building blocks Built-in functions Data Types Strings Operators Conditional statements Loop statements Functions Arrays Understaing Objects Date Object Number Object Math Object String Object Window Location Navigator History DOM Basics Forms
   Programs
Basic Control Loops Functions Arrays Examples Projects Quick Ref.
   Exercises
Variables Data Types Operators Decision Loops Reeborg's World



JavaScript Basics

Till now, we have covered the history and introduction of JavaScript. In this lession we discusses fundamental building blocks such as learning how to declare variables, using data types and manipulating them.

Character Set:

A character set defines the valid characters that can be used in source programs or interpreted when a program is running. The JavaScript uses the 16-bit representation of the Unicode character set for programming; this allows the programmer to use certain symbols as identifiers in any language that are supported by UNICODE like Π (pi) or λ (lambda). Unicode character set is a superset of the ASCII character set. For code portability and ease of use, mostly programmers use ASCII character set in their code.

Whitespace:

Whitespaces are used to separate different tokens present in the code, and the JavaScript interpreter ignores whitespaces found within the code segments or between tokens in the program. This allows us to use line breaks and whitespaces intentionally to indent our code and make it easier to understand. It helps in making the code neat and consistent for use.

Note: A token consists of an identifier, keyword, punctuation, literal or operator.

Comments:

Comments are non-executable statements in a program.A comment is text that describes what the program or a particular part of the program is trying to do and is ignored by the JavaScript interpreter. Comments are commonly usedfor specifying the name of the program, your name and the date you created the program,notes to yourself, or instructions to future programmers who may need to modify yourwork.

When you are working with long scripts, comments make it easier to decipher how a program is structured.Comments are used to helpyou and other programmers understand, maintain, and debug scripts.

JavaScript uses two types of comments:

Single-line comments and block comments.

Single-line comments start with a double slash:

Example: Try It

// This is a comment

For a block of comments, use the /* */ symbols:

Example: Try It

/* This is a block of comments
that continues for a number of lines
*/

Case Sensitivity:

JavaScript is a case-sensitive language, i.e. name, Name, NAME and NaMe are all different from one another. While writing your code, be aware of the capitalization of letters. Mostly, the code is written in lowercase letters because it is easy to read and avoids unnecessary complexity. Standard coding practice is advised for variable and function naming. firstNumber and addNumbers() are examples of camel casing convention for naming a variable and function, respectively.

Semicolons:

Most languages like C and Java use semicolons to terminate a line of code. Unlikely, JavaScript has optional requirement of semicolon and thus allows JavaScript flexibility to the developer. However, if you are writing multiple statements in a single line, then semicolons are used to tell the interpreter that there are multiple statements in the line, which need execution separately.

It is considered good JavaScript programming practice to end every statement with a semicolon. The semicolon serves to identify the end of each statement, making it easier for a programmer to the code.

Literals:

Literal is simply a source code representation of a value of a type. The value of literal is used as is in the program and does not have a type. The literals can be numeric, decimal, string and Boolean. The example is given next.

89 		//Integer Literal 
7.99 	//Floating Point Literal
"Hello JavaScript" 	//String Literal 
True   //Boolean Literal

Identifiers:

Identifiers are the names given to the literals, variables, function, property or a class. The name is used to uniquely identify a variable, function, property or a class. Identifiers are unique throughout the scope, and following are strict naming conventions that must be followed while naming an identifier.

  • Identifier name must start with a letter (a–z or A–Z), underscore (_) or a dollar ($) sign.
  • You can use numbers in an identifier but not as the first character. After first letter (a–z, A–Z, _, $), we can use digits (0–9).
  • Identifier names are case sensitive.
  • You cannot include spaces in an identifier.
  • Reserved keywords cannot be used as identifier.
name; 	    //valid name 
Name;	    //valid “name” and “Name” are different 
_id; 		//valid name 
#id; 		//not allowed 
_revisedID	// allowed 
void;		//not allowed, ‘void’ is a reserved keyword 

Reserved Words:

Reserved words (also called keywords) are special words that are part of the JavaScript language syntax. As just noted, reserved words cannot be used for identifiers.

abstract		boolean		break		byte		case		
char			class		const		continue	debugger	
delete			do		double		else		enum		
extends			false		final		finally		float		
function		goto		if		implements	import		
instanceof		int		interface	let		long		
new			null		package		private		protected	
return			short		static		super		switch		
this			throw		throws		transient	true		
typeof			var		void		volatile	while		
yield			catch		default     	export		for
in			native		public		try		with

Variables

Variables are the names given to storage locations in JavaScript. These storage locations can then be used to store any type of data by directly referring them via their assigned names.

The variables names are provided using identifier naming conventions. JavaScript is a loosely typed language, and there is no need to provide type of the variables while declaring them.

Declaring and Initializing Variables

Before you can use a variable in your code, you have to create it. In JavaScript, you usually use the reserved keyword var or let to create variables.

For example, to create a variable named firstName, you use this statement: Try It

let firstName;

Using the let keyword to create a variable is called declaring the variable. When you declare a variable, you can also assign a specific value to, or initialize, the variable by adding an equal sign ( =) after the variable name, followed by the value you’re assigning to thevariable, as follows:

let firstName = "SriRam";

The equal sign in the preceding statement is called an assignment operator because it assigns the string value on the right side of the expression to the variable on the left side of the expression. The value you assign to a variable can be a literal string or a numeric value.

When you assign a literal string value to a variable, you must enclose the text in quotation marks, just as when you use a literal string with the document.write() method. However, when you assign a numeric value to a variable, do not enclose the value in quotation marks or JavaScript will treat the value as a string instead of a number. The following statement assigns the numeric value 16 to the age:

let  age=16;

You can declare multiple variables in a statement using a single let keyword followed by a series of variable names and assigned values separated by commas.

For example, the followingstatement creates several variables using a single let keyword:

let name= "Sriram", age= 16, height= 150.5;

The values, or data, contained in variables are classified into categories known as data types.

Displaying Variables:

Displaying a variable in Browser window:

We can use document.write()method to display a variable value.

Example: Try It

let age = 12;
document.write(age);

Note: To display a variable value, we can pass the variable name to the document.write()method but without enclosing it in quotation marks.

You’ll commonly want to combine literal text with variable values in your web documents. You can use a plus sign ( + ) with the document.write() method to combine a literal string with a variable containing a numeric value.

Example: Try It

document.write("<p>Your age is " + age + " years.</p>");

In addition to using a plus sign to combine a literal string with the numeric value of a variable, you can also use a plus sign to perform arithmetic operations involving variables that contain numeric values.

Example: Try It

let theoryMarks= 750;
let practicalMarks= 175;

let totalMarks= theoryMarks+ practicalMarks;
document.write("<p>Your total marks are: " +totalMarks+ ".</p>");

Modifying Variables:

We can change the variable’s value at any point in a script by using a statement that includes the variable’s name, followed by an equal sign, followed by the value you want to assign to the variable.

Example: Try It

let age = 12;
document.write(<p>Your age is  + age +  years.</p>);
age = 13;
document.write("<p>Your age is " + age + " years.</p>");

Naming Conventions for JavaScript Variables

  • A Variable name must start with a letter (a–z or A–Z), underscore (_) or a dollar ($) sign.
  • You can use numbers in a variablebut not as the first character. After first letter (a–z, A–Z, _, $), we can use digits (0–9).
  • Variable names are case sensitive.
  • You cannot include spaces in a variable.
  • Reserved keywords cannot be used as a variable.

Variable Scope:

Scope describes where a variable is visible, or where it can be used, within the program. A variable's scope can be either global or local.

A global variable is one that is declared outside a function and is available to all parts of your code. A local variable is declared inside a function and is available only within the function in which it is declared.

A Local variables cease to exist when a function ends. If you attempt to use a local variable outside the function in which it is declared, browsers log an error message to the console.

let, var, and const

let and var are both used for variables that might have a new value assigned to them somewhere in the program. The difference between let and var is var has global scope and let has block scope.

There are few more differences between the variables declared using varandletsuch as the following:

  • The variable can be re-declared if created using var keyword, while it is not possible with the variables created using the let keyword.
  • We can use var keyword to create global or local variable by de-fining it outside or inside the block. This is not possible in case of let declared variables as they are always local within a block and cannot be accessed using other objects.

On the other hand, constant is used for variables that only get a value assigned once—for example, the value of pi, which will not change. If you try reassigning a value declared with const, you will get an error:

Example: Try It

const  pi = 3.14;