Intro-to-Javascript
Intro-to-Javascript
Most of the time, a JavaScript application needs to work with information. Here are
two examples:
1. An online shop – the information might include goods being sold and a
shopping cart.
2. A chat application – the information might include users, messages, and
much more.
Variables are used to store this information.
A variable
A variable is a “named storage” for data. We can use variables to store goodies,
visitors, and other data.
To create a variable in JavaScript, use the let keyword.
The statement below creates (in other words: declares) a variable with the name
“message”:
let message;
Now, we can put some data into it by using the assignment operator =:
let message;
message = 'Hello'; // store the string 'Hello' in the variable named message
The string is now saved into the memory area associated with the variable. We can
access it using the variable name:
let message;
message = 'Hello!';
alert(message); // Hello!
We can also declare multiple variables in one line:
let user = 'John', age = 25, message = 'Hello';
That might seem shorter, but we don’t recommend it. For the sake of better
readability, please use a single line per variable.
The multiline variant is a bit longer, but easier to read:
let user = 'John';
let age = 25;
let message = 'Hello';
Some people also define multiple variables in this multiline style:
let user = 'John',
age = 25,
message = 'Hello';
…Or even in the “comma-first” style:
let user = 'John'
, age = 25
, message = 'Hello';
Technically, all these variants do the same thing. So, it’s a matter of personal taste
and aesthetics.
var instead of let
In older scripts, you may also find another keyword: var instead of let:
var message = 'Hello';
The var keyword is almost the same as let. It also declares a variable but in a
slightly different, “old-school” way.
There are subtle differences between let and var, but they do not matter to us yet.
We’ll cover them in detail in the chapter The old "var".
A real-life analogy
We can easily grasp the concept of a “variable” if we imagine it as a “box” for data,
with a uniquely-named sticker on it.
For instance, the variable message can be imagined as a box
labelled "message" with the value "Hello!" in it:
We can put any value in the box.
We can also change it as many times as we want:
let message;
message = 'Hello!';
alert(message);
When the value is changed, the old data is removed from the variable:
We can also declare two variables and copy data from one into the other.
let hello = 'Hello world!';
let message;
alert($ + _); // 3
Examples of incorrect variable names:
let 1a; // cannot start with a digit
alert(num); // 5
This is a bad practice and would cause an error in strict mode:
"use strict";
// embed a variable
alert( `Hello, ${name}!` ); // Hello, John!
// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3
The expression inside ${…} is evaluated and the result becomes a part of the
string. We can put anything in there: a variable like name or an arithmetical
expression like 1 + 2 or something more complex.
Please note that this can only be done in backticks. Other quotes don’t have this
embedding functionality!
alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)
We’ll cover strings more thoroughly in the chapter Strings.
There is no character type.
In some languages, there is a special “character” type for a single character. For
example, in the C language and in Java it is called “char”.
In JavaScript, there is no such type. There’s only one type: string. A string may
consist of zero characters (be empty), one character or many of them.
Boolean (logical type)
The boolean type has only two values: true and false.
This type is commonly used to store yes/no values: true means “yes, correct”,
and false means “no, incorrect”.
For instance:
let nameFieldChecked = true; // yes, name field is checked
let ageFieldChecked = false; // no, age field is not checked
Boolean values also come as a result of comparisons:
let isGreater = 4 > 1;
alert(age); // "undefined"
…But we don’t recommend doing that. Normally, one uses null to assign an “empty”
or “unknown” value to a variable, while undefined is reserved as a default initial
value for unassigned things.
Objects and Symbols
The object type is special.
All other types are called “primitive” because their values can contain only a single
thing (be it a string or a number or whatever). In contrast, objects are used to store
collections of data and more complex entities.
Being that important, objects deserve a special treatment. We’ll deal with them
later in the chapter Objects, after we learn more about primitives.
The symbol type is used to create unique identifiers for objects. We have to mention
it here for the sake of completeness, but also postpone the details till we know
objects.
The typeof operator
The typeof operator returns the type of the operand. It’s useful when we want to
process values of different types differently or just want to do a quick check.
A call to typeof x returns a string with the type name:
typeof undefined // "undefined"
typeof 0 // "number"
o string for strings. A string may have zero or more characters, there’s
no separate single-character type.
o boolean for true/false.
alert(`You are ${age} years old!`); // You are 100 years old!
In IE: always supply a default
The second parameter is optional, but if we don’t supply it, Internet Explorer will
insert the text "undefined" into the prompt.
Run this code in Internet Explorer to see:
let test = prompt("Test");
So, for prompts to look good in IE, we recommend always providing the second
argument:
let test = prompt("Test", ''); // <-- for IE
confirm
The syntax:
result = confirm(question);
The function confirm shows a modal window with a question and two buttons: OK
and Cancel.
The result is true if OK is pressed and false otherwise.
For example:
let isBoss = confirm("Are you the boss?");
Value Becomes…
undefined NaN
null 0
Whitespaces (includes spaces, tabs \t, newlines \n etc.) from the start and end are
string removed. If the remaining string is empty, the result is 0. Otherwise, the number is
from the string. An error gives NaN.
Examples:
alert( Number(" 123 ") ); // 123
alert( Number("123z") ); // NaN (error reading a number at "z")
alert( Number(true) ); // 1
alert( Number(false) ); // 0
Please note that null and undefined behave differently here: null becomes zero
while undefined becomes NaN.
Most mathematical operators also perform such conversion, we’ll see that in the
next chapter.
Boolean Conversion
Boolean conversion is the simplest one.
It happens in logical operations (later we’ll meet condition tests and other similar
things) but can also be performed explicitly with a call to Boolean(value).
The conversion rule:
Values that are intuitively “empty”, like 0, an empty string, null, undefined,
and NaN, become false.
Other values become true.
For instance:
alert( Boolean(1) ); // true
alert( Boolean(0) ); // false
showMessage();
showMessage();
The call showMessage() executes the code of the function. Here we will see the
message two times.
This example clearly demonstrates one of the main purposes of functions: to avoid
code duplication.
If we ever need to change the message or the way it is shown, it’s enough to modify
the code in one place: the function which outputs it.
Local variables
A variable declared inside a function is only visible inside that function.
For example:
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
function showMessage() {
let message = 'Hello, ' + userName;
alert(message);
}
function showMessage() {
userName = "Bob"; // (1) changed the outer variable
showMessage();
function showMessage() {
let userName = "Bob"; // declare a local variable
alert( userName ); // John, unchanged, the function did not access the outer variable
Global variables
Variables declared outside of any function, such as the outer userName in the code
above, are called global.
Global variables are visible from any function (unless shadowed by locals).
It’s a good practice to minimize the use of global variables. Modern code has few or
no globals. Most variables reside in their functions. Sometimes though, they can be
useful to store project-level data.
Parameters
We can pass arbitrary data to functions using parameters.
In the example below, the function has two parameters: from and text.
function showMessage(from, text) { // parameters: from, text
alert(from + ': ' + text);
}
// the value of "from" is the same, the function modified a local copy
alert( from ); // Ann
When a value is passed as a function parameter, it’s also called an argument.
In other words, to put these terms straight:
A parameter is the variable listed inside the parentheses in the function
declaration (it’s a declaration time term).
An argument is the value that is passed to the function when it is called (it’s a
call time term).
We declare functions listing their parameters, then call them passing arguments.
In the example above, one might say: “the function showMessage is declared with
two parameters, then called with two arguments: from and "Hello"”.
Default values
If a function is called, but an argument is not provided, then the corresponding
value becomes undefined.
For instance, the aforementioned function showMessage(from, text) can be called
with a single argument:
showMessage("Ann");
That’s not an error. Such a call would output "*Ann*: undefined". As the value
for text isn’t passed, it becomes undefined.
We can specify the so-called “default” (to use if omitted) value for a parameter in
the function declaration, using =:
function showMessage(from, text = "no text given") {
alert( from + ": " + text );
}