Basics of
Week 1
Day 3
Segment 1
Basics
- What is JS
- Expressions Versus Statements
- Control Flow Statements and Blocks
- Comments
- How to write good comments
- Why comment should not be written
- Why comment should not be written
What is JavaScript
ECMAScript is the official name for JavaScript. A new name became necessary because there is a trademark on JavaScript (held originally by Sun, now by Oracle).
Created by Brendan Eich
JavaScript means the programming language.
ECMAScript is the name used by the language specification.
Overview of the Syntax
// Two slashes start single-line comments
var x; // declaring a variable
x = 3 + y; // assigning a value to the variable `x`
foo(x, y); // calling function `foo` with parameters `x` and `y`
obj.bar(3); // calling method `bar` of object `obj`
// A conditional statement
if (x === 0) { // Is `x` equal to zero?
x = 123;
}
// Defining function `baz` with parameters `a` and `b`
function baz(a, b) {
return a + b;
}
Expressions versus Statements
- Statements “do things.” A program is a sequence of statements.
var x;
- Expressions produce values.
3 * 6
- Example
var x;
if (y >= 0) {
x = y;
} else {
x = -y;
}
var x = y >= 0 ? y : -y;
Semicolons
- Semicolons are optional in JavaScript.
- However, I recommend always including them, because otherwise JavaScript can guess wrong about the end of a statement.
- Semicolons terminate statements, but not blocks.
- There is one case where you will see a semicolon after a block:
- a function expression is an expression that ends with a block.
- If such an expression comes last in a statement, it is followed by a semicolon:
// Pattern: var _ = ___;
var x = 3 * 7;
var f = function () { }; // function expr. inside var decl.
function sum(a, b) {
return
a + b
}
Example
Expected Output
> sum(4,5)
9
function sum(a, b) {
return
{
sum: a+b
}
}
Example
Expected Output
> sum(4,5)
{ sum: 9 }
Variables and Assignment
- Variables in JavaScript are declared before they are used using var keyword.
- You can declare a variable and assign a value at the same time
var foo = 6;
foo = 4; // change variable `foo`
x += 1;
x = x + 1; // Compound Assignment Operators
Identifiers and Variable Names
Identifiers are names that play various syntactic roles in JavaScript.
- Roughly, the first character of an identifier can be any Unicode letter, a dollar sign ($), or an underscore (_).
- Subsequent characters can additionally be any Unicode digit. (except reserved words.)
Primitive Values Versus Objects
- JavaScript makes a somewhat arbitrary distinction between values:
- The primitive values are booleans, numbers, strings, null, and undefined.
- All other values are objects.
A major difference between the two is how they are compared; each object has a unique identity and is only (strictly) equal to itself:
> var obj1 = {}; // an empty object
> var obj2 = {}; // another empty object
> obj1 === obj2
false
> obj1 === obj1
true
undefined and null
- Most programming languages have values denoting missing information.
- JavaScript has two such “nonvalues,” undefined and null.
- undefined means “no value.”
- Uninitialized variables are undefined:
- Missing parameters are undefined
- If you read a nonexistent property, you get undefined
> var foo;
> foo
undefined
> function f(x) { return x }
> f()
undefined
> var obj = {}; // empty object
> obj.foo
undefined
null means “no object.” It is used as a nonvalue whenever an object is expected (parameters, last in a chain of objects, etc.).
typeof results
Control Flow Statements and Blocks
For control flow statements, the body is a single statement. Here are two examples:
if (obj !== null) obj.foo();
while (x > 0) x--;
However, any statement can always be replaced by a block, curly braces containing zero or more statements.
if (obj !== null) {
obj.foo();
}
while (x > 0) {
x--;
}
Conditional and Loop Statements
The if statement has a then clause and an optional else clause that are executed depending on a boolean condition:
if (myvar === 0) {
// then
} else if (myvar === 1) {
// else-if
} else if (myvar === 2) {
// else-if
} else {
// else
}
The following is a switch statement. The value of fruit decides which case is executed:
switch (fruit) {
case 'banana':
// ...
break;
case 'apple':
// ...
break;
default: // all other cases
// ...
}
The for loop has the following format:
Values
• Numbers
• Strings
• Booleans
• Objects
• null
• undefined
Numbers
-
Only one number type
-
No integers
-
-
64-bit floating point
-
IEEE-754 (aka “Double”)
-
Special Numbers are
-
NaN
-
Infinity
-
-
Does not map well to common understanding of arithmetic:
-
0.1 + 0.2 = 0.30000000000000004
-
Infinity is larger than any other number (except NaN). Similarly, -Infinity is smaller than any other number (except NaN).
Strings
- Strings can be created directly via string literals.
- Those literals are delimited by single or double quotes.
- The backslash (\) escapes characters and produces a few control characters.
- Single characters are accessed via square brackets:
'abc'
"abc"
'Did she say "Hello"?'
"Did she say \"Hello\"?"
'That\'s nice!'
"That's nice!"
'Line 1\nLine 2' // newline
'Backlash: \\'
> var str = 'abc';
> str[1]
'b'
> var messageCount = 3;
> 'You have ' + messageCount + ' messages'
'You have 3 messages'
> var str = '';
> str += 'Multiple ';
> str += 'pieces ';
> str += 'are concatenated.';
> str
'Multiple pieces are concatenated.'
> 'abc'.slice(1) // copy a substring
'bc'
> 'abc'.slice(1, 2)
'b'
- The property length counts the number of characters in the string.
- Strings are concatenated via the plus (+) operator, which converts the other operand to a string if one of the operands is a string.
- Strings have many useful methods
JavaScript’s Type System
Static Versus Dynamic
JS Types
Static Typing Versus Dynamic Typing
Static Type Checking Versus Dynamic Type Checking
Coercion
Functions
-
Roles of functions
Functions
Methods
Constructor/object factories
Factory Functions vs Constructor Functions vs Classes
Params vs Arguments
-
Defining Functions
Function Expressions
Function Declarations
The Function Constructor
"Hoisting"
More Control over Function Calls: call(), apply(), and bind()
arguments
this inside function
The Scope of a Variable
-
closures
Why it's required in JS
What are first class functions
Basics of JS (Week 1, Day 3, Segment 1)
By Amal Augustine
Basics of JS (Week 1, Day 3, Segment 1)
- 194