JavaScript is a high-level scripting language, which means that it is far removed from the low-level operations of memory management and garbage collection, and it's a scripting language because the code you write is never compiled into a binary results, but rather run in real-time by the web browser. We use JavaScript to write and execute routines we call functions. The language is also object-oriented, in which objects have predefined methods and properties that we can use while coding. It's also important to remember that all of the JavaScript code we write is
case sensitive, so watch out for those typos.
Simple Object Properties, Methods, and Functions
We have already begun to explore some of the simple object properties, methods, and functions that are built into JavaScript.
- alert(): We can use the alert() function to display a message in a pop-up fashion. This is very annoying from a user experience perspective, and should be avoided in virtually every situations.
- prompt(): This is the equivalent of alert(), but it asks the user for some input. This is pretty outdated, and if you want input from the user, you should probably just use a form.
- console.log(): This is the preferred technique to test output in your webpage, as it won't disrupt the user experience or the loading of page elements, and it will display nicely inside of the developer tools panel.
- document.querySelector(): We use this method to get a reference to an object (an HTML element in our page) so that we can modify it.
- document.querySelector().addEventListener(): We chain these two methods together in order to first get an object reference and then apply a new event listener to that object.
JavaScript Locations
- Inside the <head> tags: Ensures that your JavaScript is fully loaded before the HTML elements in the body are.
- Inside the <body> tag: Will load and execute after the HTML elements above it have been loaded, but before the HTML elements after it have been loaded.
- Inside of event listeners: Executes code upon some user interaction triggering an event or a timed event that can occur once or on repeated regular intervals.
- Inside of a separate .js file: Just like how we can keep CSS in a file separate from our HTML, we can do the same with our JavaScript. But more on that later.
Fundamental JavaScript Concepts
- Comments: Just like how you can enter comments in HTML using the <-- --> syntax, we can add comments or comment out code in JavaScript by either placing // before a line, or wrapping your comment/code with /* */ which means it will not be executed as JavaScript.
- Variables: Variables are containers that can store information like text or numbers, even objects from pages, as well as delayed code within functions. Variables are generally created with the var, let, or const command. We can read and write to variables in order to save and retrieve different kinds of information. Data types in JavaScript include Strings, Numbers, Booleans, Nulls, Objects, Functions, and Arrays.
- Functions: Functions contain a set of JavaScript instructions which can be called at a later time. This is the best way to be able to reuse code. Functions can be passed input data in the form of arguments, and functions can return output data in the form of a return.
Programming Fundamentals
Variables
- Data storage vessels that can hold numbers, strings, booleans, object references, arrays, etc.
- Initially format or initialize variables with "var" - but ONLY the first time. So you can var favnumber or var favnumber = 34.
- Use = operator to set values. Use quotes to specify string values (rather than numeric values).
- Variable names must begin with a letter, but can contain numbers in their names. A variable name also CANNOT contain spaces OR hyphens in them. So favcolor, text2 and my2go are valid variable names, but 2go , fav color (with a space) , and my-name are not valid variable names.
- Variables created/set with numbers are considered to hold numeric data. Data stored in variables with quotes are considered to hold string data.
- var temp2='2'; temp2 = temp2 + 2; document.write (temp2);
- var temp2=2; temp2 = temp2 + 2; document.write (temp2);
- Best practice is to use descriptive variable names for clarity in your programming. Fname, lname, email and address are better variable name choices than f, l, em and a.
- Example #1: Below shows three DIFFERENT ways of building and then outputting a variable... all three are equally valid:
<script>
var myname = ""
myname = myname + "My name is ";
myname = myname + "James";
myname = myname + " ";
myname = myname + "Bond";
console.log(myname);
var myname = " My name is James Bond";
console.log(myname);
var myname = " My name is " + "James" + " " + "Bond";
console.log(myname);
</script>
- Example #2: In a page first a prompt assigns user-specified data to a variable, then displays that variable.
<script>
var variable1 = prompt('Please enter value for variable varA');
console.log('Variable variable1 is now set to ' + variable1);
</script>
Expressions
- An expression can be strings, variables, numbers and combinations of them.
- Operators define how expressions interact and are evaluated:
- = (equal) sign assigns values to variables or object properties.
- + (plus) and - (minus) perform calculations on expressions.
- < and > compare expressions.
- Evaluating an expression means returning its value. You can evaluate the value of a variable, an object, a string, or combinations of them.
Arithmetic Operators
- When arithmetic operators are used with expressions the result are value judgments of those strings:
- variable1 + variable2
- variable1 + "phrase or string"
- "1 + 1" = 1 + 1
- var num = 1 + 1
- + means to add or join expressions
- - means to subtract expressions
Comparison Operators
- When comparison operators are used with expressions the expressions are evaluated and a true or false answer results:
- var large = 12;
- var small = 2;
- alert(large < small);
- == evaluates if the expressions are equal
- != evaluates if the expressions are not equal
- > evaluates greater than
- >= evaluates greater than or equal to
- < evaluates less than
- <= evaluates less than or equal to
Functions & Methods
- Methods and functions are called by their name followed by the parentheses. When you call (activate) a function OR a method you MUST include parentheses for arguments, even if you don't have any information to pass along. For instance, alert() or alert('Test message').
- Methods are pre-written routines (or "mini programs") already stored in Javascript.
- Some methods are just one name, such as alert, whereas methods are called with a parent object preceding it, such as window.close() ... i.e. close() is not a method, but window.close() is.
- The "arguments" of a method or function are pieces of data (none, one or more) that you pass along to the routine. For instance, when you call the alert method you need to tell the program WHAT to display in the alert. So you pass the "message" as the sole argument in an alert call. The window.close() method does not have any argumetns (nothing else you need to tell it about closing a window), so the parentheses are always empty when you call that method. But regardless of whether a method (or function) has any arguments, you must always provide or represent that format through parentheses.
- Functions are routines that YOU write. You must define them in a script block BEFORE you call them.
- When you plan out a function, you must determine how many pieces of information the function you are writing will need to know/receive. When defining a function, you can write it to expect no arguments, one argument, two arguments, etc.
- Below is an example of a function called scaleit that takes any image and scales it to 100x100. The first function scales down a specific image on the page (the id of a specific image is hard-coded into the script):
function scaleit(){
theobj = document.querySelector('#theimage'); // store the object theimage into a variable
theobj.style.width = "100px"; // access the width and height style properties of the
theobj.style.height = "100px"; // object (stored in the variable) and set new values (100px)
}
- This next function is written to receive one piece of information (the name of the image):
function scaleit(imageid){
theobj = document.querySelector(imageid);
/*
Reminder: querySelector() accepts a full css selector.
So that would be "#thepic" NOT "thepic"
Or else you would need to ADD the # to the front such as
"#" + imageid
*/
theobj.style.width = 100px;
theobj.style.height = 100px;
}
- Below is another version that receives THREE pieces of information: the name of the image, the desired width and the desired height:
function scaleit(imageid, w, h){
theobj = document.querySelector(imageid);
theobj.style.width = w;
theobj.style.height = h;
}