Javascript Variables

Storing & Manipulating Data With Variables

Variables are containers for storing data.  A variable name is a label that points to this data that will allow you to access and manipulate this stored data. Creating a variable is called declaring it. You declare a variable in JavaScript by using the var keyword. Generally it’s best practice to declare all variables at the beginning of a script. All variables must be identified with a unique name. To assign a value to the variable, use the = sign. A variable declared without a value will have the value undefined. It’s best practice to end all lines of code in JavaScript with a ; semicolon.  It’s not required but it’s considered best practice.

 

There are 3 ways to declare a variable in JavaScript.

  • Var: Global Scope – Can be accessed from anywhere.
  • Let: Local Scope – Only lets you use the variable within the block you declared it in. (Best practice to avoid naming collisions)
  • Const: A variable that can not be changed.

The general rules for creating names for variables are:

  • Variable names can contain letters, digits, underscores, or a dollar sign.
  • Names must begin with a letter and not a number.
  • Names can also begin with $ (but that’s usually reserved for JQuery)
  • Names are case sensitive so (Price and price are different variables)
  • Reserved keywords cannot be used as variable names.
  • It’s best practice to use Camel Case for variable names. First letter of the first word is small. First letter of all following words should be capitalized.

JavaScript Provides 7 Different Data Types:

You can get the type of a variable using the typeof keyword: typeof variable;

  • undefined: variable that hasn’t been defined.
  • null: Means nothing. Set a variable to be nothing.
  • boolean: Set a variable to true or false.
  • number: Variable that contains any number.
  • string: Variable that contains any text.
  • symbol: A symbol may be used as an identifier for object properties and dynamically produces an anonymous, unique value.
  • object: An object can store key value pairs.
Declaring & Assigning Variables.
// Initializes a variable. The value is set to undefined.
// Global Variable or to enclosing function
var variable; 

// Block Scope Local Variable
let variable2 = "Local Scope";

// A variable that can not be changed
const pie = 3.1415926535897932384626433;

// Declaring many variables in one statement.
var person = "Cindy Smith", carType = "Ford", price = 35000;

// Lets you see the value of the variable in the console. Great to debug your code and make sure things are working.
console.log(variable);
console.log(variable2);
console.log(pie);

// Console log multiple variables in one statement
console.log("PERSON: " + person + " CAR TYPE: " + carType  + " PRICE: " + price);
String Variables In Javascript
// String (Text) ---------------------------------------------------------
var customer = "Cindy Smith";
var message = 'Yes I am!';
  
// Concatenate Strings - Joining Strings Together
var customerMessage = customer + ": " + message;
var fullName = "John" + " " + "Doe";
var ourString = "First sentence. " + "Second sentence."
var myStr = "Hello, my name is " +  fullName + " and i'm a happy coder!";

console.log(customer);
console.log(message);
console.log(customerMessage);
console.log(fullName);
console.log(ourString);
console.log(myStr);
console.log(typeof customer); // Gets type of variable
String Variables in Javascript
Find The Length Of A String
var myFirstName = "Nathan Ergang";
lengthOfFirstName = myFirstName.length;

console.log("My first name is " + myFirstName + ". That has " + lengthOfFirstName + " characters in it.");

// CONSOLE: My first name is Nathan Ergang. That has 13 characters in it.
Advanced Strings
// Add HTML to a variable
// Using a backtick is the easiest way to add "QUOTES" into a sting.
var HTML = `<a href="http://www.GreenMarketing.ca"> Link </a>`;
 
// You could also just use single quotes.
var HTML = '<a href="http://www.GreenMarketing.ca"> Link </a>';
 
// You can also use an escape character () BACK SLASH.
// It makes the code harder to read so I prefer the first 2 options.
var HtmlLink = "<a href="http://www.GreenMarketing.ca"> Link </a>";
 
// When you write inside ${} this is called a template literal.
// It has some special features the result will be computed.
 
var text = `half of 100 is ${100 / 2}`;
console.log(text);    // Console: half of 100 is 50

Escape characters inside a sting.

Some chatacters don't work inside a sting and need to be escaped to work.

Quote  \’
Double Quote \”
Back Slash  \\
New Line  \n
Carriage Return
(Simular to new line)
 \r
Tab \t
Backspace \b
Form Feed
A form feed is a page-breaking. Forces the printer to start a new page.
\f

 

Bracket Notion

Get a character within a specific index of the string. Remember that javaScript uses ZERO BASED INDEXING which starts at 0 not 1.

var myFirstName = "Nathan Ergang";
firstLetterOfTheString = myFirstName[0];
lastLetterOfTheString = myFirstName[myFirstName.length -1];

console.log("The first letter of the sting is " + firstLetterOfTheString + " and the last letter is " + lastLetterOfTheString + ".");
// CONSOLE: The first letter of the sting is N and the last letter is g.
 
/* ERROR: You can not change an individual character's value. This will give an error or won't take any effect */
myFirstName[0] = "E";

Numbers & Variables In Javascript

In JavaScript, just like in algebra, we can use variables in an expression.

Number Variables
// Numbers
var price_1 = 3;
var price_2 = 10.99;
var total = price_1 + price_2;

console.log(price_1 + " PLUS " + price_2 + " = " + total);
console.log(typeof total); // Gets type of variable
Number Variables Javascript
Javascript Expressions
var totalCost = price_1 + price_2;
var sum = 10 + 12 + 33;
var difference = 50 - 10;
var product = 10 * 10;
var quotient = 100 / 10;

// Increment a number
var myIncrement = myIncrement + 1;
myIncrement++;       	// shorthand
 
// Decrements a number
var myDecrement = myDecrement - 1;
myDecrement--;       	// shorthand 

// Find the remainder
var remainder = 44 % 10;	//4
 
// Determine if a number is even or odd by checking the remainder of 2
var remainder = 44 % 2;	

// Variable = Itself + a number
var a = a + 40;
a += 40;  	//Shorthand
 
// Variable = Itself - a number
a = a - 40;
a -= 40;  	//Shorthand
 
// Variable = Itself multiplied by a number
a = a * 40;
a *= 40;  	//Shorthand
 
// Variable = Itself divided by a number
a = a / 40;
a /= 40;  	//Shorthand

Facebook Video