JavaScript Programming/Variables and Expressions
This lesson introduces JavaScript variables, data types, expressions, and operators.
Objectives and Skills
editObjectives and skills for this lesson include:[1]
- Apply JavaScript best practices
- Comments; indentations; naming conventions; noscript; constants; reserved keywords; debugger keyword; setting breakpoints; console.log
- Declare and use variables of primitive data types
- Number; Boolean; String; Null; Undefined; typeof operator; type checking functions; use strict; converting between data types; formatting numbers; string operations; single quote vs double quote (nesting); initialization
- Complete or debug code that uses assignment and arithmetic operators
- Assignment; increment; decrement; addition; subtraction; division; multiplication; modulus; compound assignment operators.
Readings
editMultimedia
edit- Variables
- YouTube: JavaScript Tutorial for Beginners - 03 - Variables
- YouTube: JavaScript Tutorial for Beginners - 04 - Variables Part 2
- YouTube: JavaScript Programming Tutorial 6 - Variables and Expressions
- YouTube: JavaScript Let, Const & Var
- YouTube: 7: How to Create Variables in JavaScript | JavaScript Tutorial | Learn JavaScript
- YouTube: What is a Variable? | JavaScript in less-than 3 minutes
- YouTube: Variables & Data Types | Javascript | Tutorial 6
- Data Types and Operators
- YouTube: Javascript Variables & Data Types
- YouTube: JavaScript Tutorial for Beginners - 08 - Operators
- YouTube: A Basic Calculator
- YouTube: 20 String Methods in 7 Minutes
- Input
- YouTube: Getting User Input | Javascript | Tutorial 9
- YouTube: How to accept JavaScript USER INPUT in 5 minute
- Debugging
- YouTube: Debugging JavaScript (Google Chrome and Visual Studio Code)
- YouTube: Firefox JavaScript Debugger
- YouTube: Debugging JavaScript - Chrome DevTools 101
- Type Coercion
- Expressions vs. Statements
Examples
edit- W3Schools: JavaScript Syntax
- W3Schools: JavaScript Variables
- W3Schools: JavaScript Operators
- W3Schools: JavaScript Statements
- W3Schools: JavaScript Arithmetic
- W3Schools: JavaScript Assignment
- W3Schools: JavaScript Popup Boxes
- Freecodecamp: JavaScript Popup Boxes with Examples
- W3Schools: JavaScript Debugging
- W3Schools: JavaScript Data Types
- W3Schools: JavaScript Numbers
- W3Schools: JavaScript Number Methods
- W3Schools: JavaScript Strings
- W3Schools: JavaScript String Methods
- W3Schools: JavaScript Strict Mode
- W3Schools: JavaScript Type Conversion
- W3Schools: Null vs Undefined
- JavaScript — Null vs. Undefined
- Example Code
- MDN Web Docs: Expressions and Operators
- GeeksforGeeks: Javascript Expressions
- Data types: Data Types in JavaScript
Activities
editComplete two of the following activities using external JavaScript code. Apply JavaScript best practices, including comments, naming conventions, and constants. In at least one program, prompt the user for input and use console.log() for output. In another program, prompt the user for input and use document.getElementById().innerText or document.getElementById().innerHTML for output. Use the strict directive. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.
Arithmetic
edit- Create a program that uses variables for hours and rate per hour and then calculate and displays weekly, monthly, and annual gross pay (hours * rate). Base monthly and annual calculations on 12 months per year and 52 weeks per year.[2]
- Create a program that uses variables for years, and then calculate and displays an approximate age in months, days, hours, and seconds. For example, a person 1-year-old is 12 months old, 365 days old, etc.
- Review MathsIsFun: US Standard Lengths and MathsIsFun: Metric-US/Imperial Conversions. Create a program that uses variables for a distance in miles, and then calculate and displays the distance in yards, feet, and inches, or calculate and display the distance in kilometers, meters, and centimeters.
- Review MathsIsFun: Area of Plane Shapes. Create a program that uses variables for the dimensions of different shapes and then calculate and displays the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
- Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet to a yard.[3]
- Review MathsIsFun: Order of Operations. Create a program that demonstrates the order of operations. Include parentheses, exponents, multiplication, division, addition, and subtraction in your program. Use variables for the calculations and label the output. For example, part of the program might display:
1 + 2 * 3 = 7
(1 + 2) * 3 = 9
...
Data Types
edit- Create a program that initializes different variables with integer, floating point, string, null, and undefined values. Demonstrate various operations and converting between data types. For example, user input is always a string, but adding string values of "1" + "1" is typically "11", whereas, adding numeric values of 1 + 1 is 2. Use
typeof
to label each variable and the resulting output. - Create a program that demonstrates string operations and string formatting. Define string constants or string literals that include apostrophes ('). Define string constants or string literals that include "quotes". Convert between string and numeric data types using Number() and .toFixed() with two decimal places. Concatenate string literals and variables to display output.
Debugging
edit- Use the
debugger
statement to create a breakpoint in one of the programs above. Experiment with single-stepping through the code and viewing script and global values. Add one or more variables to the watch window. - Add a breakpoint to the program somewhere after the
debugger
statement. After the program stops with the debugger, resume script execution and observe the script stopping at the breakpoint.
Lesson Summary
edit- By convention, JavaScript variable names are written in camelCase.[4]
- In JavaScript, I explored variable declarations with
let
andconst
, string properties and methods such aslength
andtoUpperCase()
, primitive data types likenumber
,string
,boolean
,null
, andundefined
, and various operators for string concatenation, arithmetic, assignment, increments, comparisons, and logical evaluations. - JavaScript Class, interface, record, and typedef names are often written in Title Case.[4]
- JavaScript constant names are written in UPPER_CASE.[5]
- JavaScript variable and constant names must be unique. These unique names are called identifiers.[6]
- Reserved words (for example, continue, debugger, break, etc.) can't serve as variable names.[6]
- Names can begin only with a letter, an underscore or a dollar sign. Names are allowed to contain numbers, but a number can't be the first character.[6]
- In Java Script names are case sensitive.[6]
- Comments, which are annotations or explanations of written code[7], are done in JavaScript using // for a single line, and /* ... */ for multiple lines.
- JavaScript has 7 data types: Number, String, Boolean, Null, Undefined, Function, and Object. Null and Undefined data types can't contain values.[8]
- There are 6 types of objects in JavaScriptː Object, Date, Array, String, Number and Boolean.[8]
- JavaScript has only 1 type of number.[9]
- With some other languages, like Java and C, there is a special “character” type. JavaScript consists of only one type, string.[10]
- The
typeof
operator is used to find the data type of the variable.[8] - JavaScript has built-in functions to work with strings and numbers[11]
- Strings are written using single or double quotation marks. Quotation marks can be used inside the string if they don't match the ones outside of it.[8] Quotation marks used inside can match the outside ones only if they are preceded by the backslash escape character.[12]
- You can convert between data types in JavaScript.[8]
- "use strict" is a literal expression that requires / enforces variable declaration. It allows for cleaner code to be written.[13]
Key Terms
edit- array
- An array is a type of variable that stores a collection of values. The position of each value inside the array is that value's index. Indexes in JavaScript always start at 0.[14]
- assignment
- Assigning a value to a variable or constant with the "=" operator.
- Boolean
- Data type which has only two values, True and False.[15]
- camel case
- Method of joining multiple words into one variable name where the first word is not capitalized and every subsequent first letter of following words are capitalized[16]
- Title case or pascal case
- Method of joining multiple words into one variable name where the first letter of every word is capitalized.[16]
- concatenation
- Method of joining two strings, data, or other text together in programming. In JavaScript, strings are concatenated using the '+' operator. [17]
- console.log
- A function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.
- constant
- A keyword introduced from ES2015, It is a container for storing a permanent data value that cannot be changed later in the program.[18]
- Equality
- An operator referencing when two values are equal, "==", this is distinct from the assignment ("=") operator referenced above.[18]
- let
- A keyword introduced from ES2015, It is used to declare a variable in JavaScript. it is used as block scoped variable while "var" is used as a function scope variable [19]
- null
- A special value which represents "nothing." It is not a reference to a null pointer.[15]
- number
- Data type in JavaScript which represents both integers and floating-point value.[15]
- object
- A variable that can contain many values.[20]
- order of operations
- A set of rules for for evaluating mathematical expressions. While different programming languages have different rules for precedence, the order of operations start from greatest precedence with parentheses, exponents, multiplication/division, and addition/subtraction.[21]
scope
The current context of the code, refers to the accessibility of functions and variables.
- string
- Can consist of one character or many. A string must be surrounded by quotation marks.[15]
- type coercion
- The automatic or implicit conversion of values from one data type to another (such as strings to numbers).[22]
- undefined
- A variable which has not been assigned a value. If a variable is simply declared, but not assigned anything, it becomes undefined.[15]
- variable
- A container for storing a data values. Variables are used to hold values in expressions. [6]
See Also
edit- Wikipedia: Variable (computer science)
- Wikipedia: Constant (computer programming)
- Wikipedia: Data type
- Wikipedia: Expression (computer science)
- Wikipedia: Statement (computer science)
- Wikipedia: Assignment (computer science)
- Wikipedia: Order of operations
- Wikipedia: Self-documenting code
- Robin Wieruch: Javascript Naming Convention
- Var, Let, and Const – What's the Difference?
- The typeof Operator
- Get Started with Debugging JavaScript in Chrome DevTools
References
edit- ↑ Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
- ↑ PythonLearn: Variables, expressions, and statements
- ↑ Wikibooks: Programming Fundamentals/Practice: Data and Operators
- ↑ 4.0 4.1 https://google.github.io/styleguide/jsguide.html
- ↑ https://google.github.io/styleguide/jsguide.html
- ↑ 6.0 6.1 6.2 6.3 6.4 W3Schoolsː JavaScript Variables
- ↑ "Comment (computer programming)". Wikipedia. 2021-01-08. https://en.wikipedia.org/w/index.php?title=Comment_(computer_programming)&oldid=999054165.
- ↑ 8.0 8.1 8.2 8.3 8.4 W3Schoolsː JavaScript Data Types
- ↑ W3Schoolsː JavaScript Numbers
- ↑ "Data types". javascript.info. Retrieved 2019-09-05.
- ↑ MDN Web Docs: Data Types and Data Structures
- ↑ W3Schoolsː JavaScript Strings
- ↑ W3Schoolsː JavaScript Use Strict
- ↑ "JavaScript Arrays". www.w3schools.com. Retrieved 2024-03-08.
- ↑ 15.0 15.1 15.2 15.3 15.4 JavaScript.Infoː Data Types
- ↑ 16.0 16.1 Microsoft: Capitalization Styles
- ↑ "What is Concatenate?". www.computerhope.com. Retrieved 2020-09-04.
- ↑ 18.0 18.1 W3Schools: JavaScript const
- ↑ "JavaScript Let". www.w3schools.com. Retrieved 2020-09-01.
- ↑ W3Schoolsː JavaScript Objects
- ↑ "Programming Fundamentals/Order of Operations - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2020-09-04.
- ↑ MDNː Type coercion