JavaScript basics
Objectives
- create comments in JavaScript source code
- explain the importance of using indentation in coding
- explain how to use strict mode in JavaScript
- discuss JavaScript objects, properties, methods, and events
JavaScript comments
There are two types of JavaScript comments. Single line comments
start with a double slash (//) and everything after that on the line
is treated as a comment. Single line comments automatically end
at the end of the line. Multiline comments start with a slash star (/*)
and end with a star slash (*/). Multiline comments may start and end
on the same line or span several lines. Multiline comments can NOT
be nested.
See W3schools.com JavaScript comments article
- examples of single line comments:
// May be the only thing on a line
var color; // may follow some JavaScript code
- examples of multiline comment:
/*
Detailed explanations of sections of code
are often multiline comments
*/
JavaScript object terminology
- JavaScript uses many object-oriented programming concepts
- object: roughly equivalent to what an object is in real life; an object
can have properties (such as a color), methods (which are things it can do,
such as add up a set of numbers), and events (such as a birthday or having
a mouse click on you)
- property: a property is something that an object "has"; please note that a
property may also be an object by itself, such as a form having a text box as
a property - and the text box will have its own set of properties
- method: a method is something that an object can do; they are roughly
equivalent to verbs
- event: something that happens, such as a mouse click, or the web page
finishing loading; JavaScript lets you write code to respond to specific
events; events are often triggered by some user action
Indentation
JavaScript doesn't care about indentation. In fact, once a library of
JavaScript code is stable, it is common to minimize the code to make it
load faster. One of the many ways code is minimized is by getting rid of
indentation. Indentation does serve an important purpose before that
point. Indentation makes code more readable and maintainable by setting
off blocks of connected code from other code surrounding it. There are
many styles that programmers use, but it is important to indent the
body of a function, the branches of an if or if/else statement, and the body
of a loop.
Strict mode
- Strict mode imposes some restrictions on JavaScript code which can help make the code more secure and stable.
- You can invoke strict mode on an entire script by using the following as the first statement: "use strict";
- You can invoke strict mode on an individual function by using the following as the first statement in the function: "use strict";
- Strict mode is not reliably implemented on all browsers yet.