JavaScript: Values and Variables
Lecture Based on JavaScript Absolute
Beginner's Guide
In This Chapter
• - Learn how to use values to store data
• - Organize code with variables
• - Understand variable naming rules
• - See examples of declaration and initialization
What Are Values?
• - Every piece of data in JavaScript is a value
• - Examples: text, numbers, punctuation
• - Values are the building blocks of all code
• - Example: alert("hello, world!");
Why Use Variables?
• - A variable is a name for a value
• - Allows reuse without duplicating data
• - Makes code easier to update
• - Example:
• var myText = "hello, world!";
• alert(myText);
Updating Variables
• - Change value in one place, update
everywhere
• - Example:
• var myText = "The dog ate my homework!";
• alert(myText);
Variable Naming Rules
• - Can start with letter, underscore (_), or dollar
sign ($)
• - Cannot start with a number
• - After first character: letters, numbers, _, $
• - No spaces allowed
• - Example names:
• var myText;
• var _counter;
• var $field;
Declaring and Initializing
• - Declare: var myText;
• - Initialize: myText = "hello, world!";
• - Can be done in one step: var myText = "hello,
world!";
• - Variables can store different data types (text,
numbers, boolean, undefined)
Key Takeaways
• - Values represent data
• - Variables store and reuse values
• - JavaScript is flexible with variable use
• - Naming rules keep code valid
• - Practice using variables to simplify your
programs