Tuesday, 28 May 2024

JavaScript: Variables

Variables are containers that store values. You start by declaring a variable with the var or the let keyword, followed by the name you give to the variable:

EXAMPLE:

var x = 100;

      or

let myVariable;


And here’s what’s happening in the example above:

  1. var is the keyword that tells JavaScript you’re declaring a variable.

  2. x is the name of that variable.

  3. = is the operator that tells JavaScript a value is coming up next.

  4. 100 is the value for the variable to store.

Note: A semicolon at the end of a line indicates where a statement ends.

You can name a variable nearly anything, but there are some restrictions:

  • A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($). Subsequent characters can also be digits (0–9).

  • Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) as well as "a" through "z" (lowercase).

EXAMPLE:

var camelCase = "lowercase word, then uppercase";

var dinner2Go = "pizza";

var I_AM_HUNGRY = true;

var _Hello_ = "what a nice greeting"

var $_$ = "money eyes";


And here are some invalid variable names — try to spot what’s wrong with each of them:

EXAMPLE

var total% = 78;

var 2fast2catch = "bold claim";

var function = false;

var class = "easy";


Using variables

After you declare a variable, you can reference it by name elsewhere in your code.

EXAMPLE:

var y = 200;

y + 202;

OutPut

402

You can even use a variable when declaring other variables.


EXAMPLE:

var x = 200;

var y = x + 2;

y;

OutPut

202


Reassigning variables

You can give an existing variable a new value at any point after it’s declared.

EXAMPLE:

var weather = "good";

weather = "bad";

weather;

OutPut

bad


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts