← Learn Javascript

Variables

How to store and compare values and data types

slides | md

Introduction

Review the following sections and perform the activities on your own or with your group.

Perform the task(s) when you see this πŸ‘‰ emoji

Learning Objectives

Students who complete this module will be able to:

  • Demonstrate how to install Javascript in a web page.
  • Explain why and how to use comments in Javascript.
  • Use Javascript to create and use variables.
  • List common syntax issues when programming Javascript.
Homework

Add Javascript to a web page

Add Javascript to a web page inside a <script> element, or load it into your page from an external .js file. The browser will run your code when it loads the page, or in response to a user’s actions.

<!-- 0-hello.html -->
<html>
<head>
<meta charset="UTF-8">
<title>Learn Javascript</title>
</head>
<body>
<h1>Javascript "hello world!"</h1>
<script>

alert("hello from script tag!");

</script>
</body>
</html>

Add Javascript to a web page

Using an external .js file is usually preferred because, like external CSS, a single file used across your whole site makes your code easier to edit and maintain. View this page demos/0-hello.html.

// 0-hello.js
console.log("Hello from an external .js!");
<!-- 0-hello.html -->
<html>
<head>
<meta charset="UTF-8">
<title>Learn Javascript</title>
</head>
<body>
<h1>Javascript "hello world!"</h1>

<script src="0-hello.js"></script>
</body>
</html>

⚠️ Order matters

Place CSS and JS into your HTML page in the following order:

<html>
<head>
<title>Learn Javascript</title>
<!-- 1. CSS in the <head> so HTML can access when it loads -->
<link rel="stylesheet" href="styles.css">
<style> h1 { color: blue; } </style>
</head>
<body>
<!-- 2. HTML tags and visible content go in the body -->
<h1>Content of your web page</h1>
<!-- 3. Javascript goes after all content to ensure HTML has loaded
and is ready to be used by your code. -->
<script> alert("Hello world!"); </script>
</body>
</html>

Keep that Console open

The Console displays a message from the console.log() function, as well as the line number where it was called in your code.

true

Errors in your code appear with a red flag and the line number where you can fix it!

true

πŸ‘‰ Try it out - Tips for using the Console

  • The Console shows hints while you type; press "Tab" to autocomplete.
  • Press up ↑ to show previous commands you entered.
  • Add multiple expressions to console.log() separated by a comma.
document.title = "hello"
console.log("abc", 123);
Keep the Console open when coding to be notified of problems with your code.

Variables

  • Use Variables to store data in your program.
  • Variables, like water bottles, can store things to use later when you need to.

Variables

true

From the left, this statement

  1. Creates a new variable named greeting and
  2. Assigns the string "hello" as the value (using the assignment operator)

The assignment process is also referred to as "binding", because the data is actually stored in the memory of the computer, not the variable.

var, let, and const

Javascript is based on the ECMAScript standard, which in ES6 added new variable declaration keywords to address issues

var (old method, still works)

  • Variables can be redeclared
  • Variable have global scope

let and const

  • You can't use a variable before it is declared.
  • Variables can only be accessed in the block { ... } they were declared.
  • const variables cannot be changed ("constant")

Update the value stored in a variable

Just like a water bottle, you can replace the value stored in a variable.

πŸ‘‰ Try it out - What is the value in num after each of these statements? Feel free to check the documentation on the + operator.

var num = 1000; // -> ?
num = num + 10; // -> ?
num += 10; // -> ?
num ++; // -> ?
num += "10"; // -> ?
Solution
  1. 1000 is stored in the new variable
  2. 1010 - 10 was added to 1000
  3. 1020 - Shorthand for the previous line
  4. 1021 - The increment operator increase by 1
  5. "102110" - Whenever you use the + operator and any string, then all data types are converted to strings and "concatenated," or merged together into one long string.

πŸ‘‰ Try it out - Examine code examples

  1. View the source of this page demos/2-variables.html
  2. Try to determine what each console.log() function will output?
  3. Open the console to verify.

Variable data types

A non-typed language like JS will infer the data type when you create a variable.

πŸ‘‰ Try it out - How to explicitly change a variable type

  1. Examine the lines below.
  2. Try to determine what each console.log() function will output?
  3. Open the console to verify.
let answer = true;
console.log(answer, typeof answer);
answer = Number(answer);
console.log(answer, typeof answer);
answer = String(answer);
console.log(answer, typeof answer);
answer = Boolean(answer);
console.log(answer, typeof answer);
Solution
true "boolean"
1 "number"
1 string
true "boolean"

πŸ‘‰ Try it out - Storing and using complex data types

You can store complex types like the Date Object in variables as well.

Run these lines in the Console to see the output. The last line concatenates the value of question, an empty space, and the return value of a logical expression.

// bind a string
let question = "Can we celebrate yet?";
// store an instance of the date object
let today = new Date();
console.log(typeof today);
// concatenate the string binding with the return value from an expression
console.log(question + " " + (today.getFullYear() > 2020))

Syntax

While slightly more forgiving than other languages, Javascript still requires your syntax to be correct or your code won’t work as expected. For example, it is a good practice to always include the trailing semicolon.

let greeting = "hello";

Read on for more tips and suggestions.

Syntax > Comments

Comments can be used to add notes about code. They are preceded by // or enclosed by /* ... */ and are not evaluated when the program runs.

// a single line comment
/* a multiline
comment */

Syntax > Whitespace

Using whitespace (spaces, tabs, and line breaks) can help make your code more readable but ignored by JS. These examples will be executed the same.

// without whitespace
if (true) { console.log(123); }
// with whitespace
if (true)
{
    console.log(123);
}

Some rich text editors will also have hidden whitespace characters that can cause errors. Copying / pasting code from Slack sometimes cause this issue.

Syntax > Smart quotes

Take care when copying / pasting from rich text editors (like Word or HTML pages) which sometimes use smart quotes (a.k.a. β€œcurly quotes”). Note in the example below how the text color formatting is broken on the first example. Smart quotes are not acceptable for wrapping string data and will cause errors.

β€œ An example string with smart quotes 😿 ”
" An example string with dumb quotes πŸ˜€ "

VS Code uses a Javascript Linter to check for these errors. You can also use websites like jshint.com or jslint.com to save hours of frustration.

πŸ‘‰ Try it out - Locate a syntax error in the console

  1. View the source of this page demos/3-syntax-quotes.html
  2. Try to determine what line number console will report for the error?
  3. Open the console to verify.

Next steps

  1. Try the Exercises below.
  2. Start working on homework listed in the schedule.
  3. Continue to the next lesson: Control Flow slides | md

Exercises

πŸ‘‰ Try it out - Practice with variables

  1. Create three variables to store your age, name, and a boolean value (e.g. the result of this statement: "I like vanilla ice cream").
  2. Concatenate them all together in one variable called sentence and log it to the console.

References

Presentation comments ...

--- ## Contents 1. [Introduction](#introduction) 1. [Add Javascript to a web page](#add-javascript-to-a-web-page) `3 min` 1. [Keep the Console open](##keep-the-console-open) `3 min` 1. [Variables](#variables) `10 min` 1. [Syntax](#syntax) `5 min` 1. [Next steps](#next-steps) 1. [Exercises](#exercises) 1. [References](#references)