Category: Bob Tabor

  • JavaScript Foundations: From Variables to Functions by Bob Tabor

    JavaScript Foundations: From Variables to Functions by Bob Tabor

    This document offers an introduction to JavaScript programming, starting with fundamental concepts like saving files, executing code in environments like Node.js, and understanding the difference between the language and its runtime environment. It progresses to explain JavaScript syntax, comparing it to English, and introduces variables, their declaration keywords (let, var, const), and naming conventions. The text then explores data types (number, string, boolean, undefined), type coercion, and essential operators for various operations. Further topics include arrays for managing lists of data, functions (declarations, expressions, immediately invoked function expressions), decision statements (if, switch, ternary), and iteration (for, while loops). It also covers variable scope, the module pattern for managing global scope issues, closures, the behavior of the ‘this’ keyword, destructuring arrays and objects, and template literals for flexible string creation. Finally, it touches upon regular expressions, built-in native objects like String and Array, constructor functions, the conceptual equivalence of classes in JavaScript, and arrow functions, concluding with a brief overview of the Date object and useful string and array methods.

    JavaScript Foundations From Variables to Functions by Bob Tabor amjadizhar blog

    JavaScript Fundamentals: A Beginner’s Guide

    JavaScript is a popular programming language, and this course is designed for absolute beginners, including those new to programming in general. It assumes some familiarity with HTML and CSS and focuses on teaching the pure JavaScript language rather than being a web development course, although JavaScript’s use in web browsers will be discussed towards the end. The course emphasizes writing console or command-line style applications to isolate the language itself from HTML and CSS complexities.

    Here are some fundamental aspects of JavaScript:

    • Tools for Development
    • You will need a web browser (Microsoft Edge or Google Chrome are recommended).
    • Node.js is required as the JavaScript runtime environment to execute code. It’s essentially the V8 JavaScript engine from Chrome with added tools for server-side functionalities, though for this course, it’s used for simple console output.
    • An authoring tool like Visual Studio Code (VS Code) is highly recommended. It’s free, cross-platform, and provides features like code coloring, code completion (IntelliSense), file management, and an integrated terminal.
    • Execution Environments JavaScript code can be executed in several environments:
    • Node.js: Typically used for server-side applications that interact with the file system, network, or handle HTTP requests/responses.
    • Web Browser: Used for dynamically interacting with HTML elements on a web page.
    • Other environments: Like Unity for video game development. It’s important to understand the distinction between the JavaScript language itself and the environment it runs in. For instance, console.log exists in both Node.js (to print to the command line) and web browsers (for debugging messages in developer tools).
    • Language Fundamentals
    • Statements and Expressions:
    • A statement is a complete instruction, like a sentence in English, ending with a semicolon. JavaScript files contain one or more statements executed sequentially.
    • A statement consists of one or more expressions.
    • An expression is made up of operators (like keywords, +, =) and operands (like variable names or function calls).
    • Examples of expressions include variable declarations (let a), value assignments (a = 4), and evaluations that return a single value (b + c).
    • Case Sensitivity: JavaScript is case-sensitive. console with a capital ‘C’ is different from console with a lowercase ‘c’.
    • Comments:
    • Single-line comments start with two forward slashes (//).
    • Multi-line comments start with /* and end with */.
    • Variables
    • A variable is an area in the computer’s memory to store and retrieve values.
    • Declaration Keywords:
    • let: The recommended keyword for declaring variables in modern JavaScript, behaving like variables in most other programming languages.
    • var: The original keyword, still widely seen in tutorials and articles, but its usage is nuanced and can lead to unexpected ramifications due to its scope behavior.
    • const: Used for variables whose values are not intended to change after initialization. Attempting to reassign a const variable will result in an error.
    • Naming Rules for Identifiers:
    • Must begin with a letter, dollar sign ($), or an underscore (_).
    • Can contain letters, numbers, dollar signs, or underscores.
    • Cannot contain spaces or other special characters.
    • Cannot be a keyword (e.g., let cannot be a variable name).
    • Are case-sensitive (x is different from X).
    • Naming Conventions (Best Practices):
    • Descriptive names: Should represent the data being stored (e.g., firstNumber instead of x).
    • Camel casing: First word lowercase, subsequent words capitalized (e.g., firstName, zipCode).
    • Consistency: Maintain a consistent naming style throughout the application.
    • Avoid relying on case: Don’t create variables like zipCode and ZipCode as separate entities, as it reduces readability.
    • Assignment Operator (=): Used to assign a value to a variable. A variable can be declared once but assigned values multiple times.
    • Initialization: Assigning a value to a variable at the moment of declaration (e.g., let x = 7). If not initialized, a variable’s value is undefined.
    • Scope (Basic): Variables have a lifespan and citizenship determined by where they are declared.
    • Variables declared in an outer scope are visible in all inner (child) scopes.
    • Variables declared in an inner scope are not available in outer scopes; they “die” and are removed from memory once their code block finishes execution.
    • Data Types
    • In JavaScript, values have data types, not the variables themselves. A variable can hold different types of values over its lifespan.
    • Primitive Data Types:
    • Number: Any positive or negative number, including decimals.
    • Boolean: true or false.
    • String: A sequence of characters, usually represented with single or double quotes (e.g., ‘hello world’).
    • Undefined: The value a variable has when declared but not yet assigned a value.
    • Null: Represents a variable that points to nothing, typically when an object reference was expected. It’s considered an object type when using typeof due to a known bug.
    • Symbol: A new primitive type in the latest JavaScript version, not covered in depth.
    • Complex Data Types:
    • Object: A collection of related properties and methods. Arrays are a type of object.
    • Function: A block of code that can be named and called. Functions are also considered a data type.
    • Type Coercion
    • JavaScript can automatically coerce (convert) data types when incompatible types are used together (e.g., adding a number and a string will convert the number to a string and then concatenate them).
    • Explicit Coercion: You can force conversion using built-in functions like parseInt() to convert a string to an integer, specifying the radix (base system, usually 10).
    • NaN (Not a Number): Returned by parseInt() or other numeric operations if the conversion or calculation results in something that isn’t a valid number. isNaN() can be used to check for this.
    • Operators
    • Assignment: = (assigns value).
    • Arithmetic: + (addition), – (subtraction), * (multiplication), / (division).
    • Increment/Decrement: ++ (increments by 1), — (decrements by 1). Can be prefix (++a, first evaluate then use) or postfix (a++, first use then evaluate).
    • Modulus (%): Returns the remainder of a division.
    • String Operators: Single/double quotes for literal strings, + for string concatenation.
    • Precedence: Parentheses () control the order of operations, similar to algebra.
    • Function Invocation: () after a function name to execute it.
    • Member Accessor: . (dot notation) to access properties or methods of an object (e.g., console.log).
    • Array Element Access: Square brackets [] to access elements in an array by index (e.g., a).
    • Logical Operators: && (AND), || (OR) for combining conditions.
    • Equality Operators:
    • == (equality): Checks if two values are equal, performing type coercion if necessary.
    • === (strict equality): Checks if two values are equal AND of the same data type, without coercion.
    • != (not equal to): Checks for inequality.
    • !== (strict not equal to): Checks for strict inequality.
    • Functions
    • A function is a named block of reusable code.
    • Function Declaration: Defined using the function keyword, an identifier (name), parameters in parentheses, and a body in curly braces (e.g., function sayHello() { … }).
    • Function Expression: A function defined as part of an expression, often assigned to a variable, and can be anonymous (without a name). Useful for callbacks.
    • Arguments/Parameters: Values passed into a function, defined within the parentheses.
    • Return Values: Functions can return a single value using the return keyword.
    • Immediately Invoked Function Expression (IIFE): A function expression that is defined and executed immediately. It’s enclosed in parentheses and followed by another set of parentheses for invocation (e.g., (function() { … })();). Often used to create a private scope.
    • Arrow Functions: A concise, shorthand syntax for writing function expressions, especially useful for simple functions or callbacks. They use => (fat arrow operator).
    • Decision Statements
    • if-else if-else: Executes different blocks of code based on conditions that evaluate to true or false.
    • switch: Evaluates an expression against multiple case values. Uses break statements to exit a case block and prevent “fall-through”.
    • Ternary Operator: A shorthand if-else statement that performs a quick inline evaluation and returns one of two values (e.g., condition ? valueIfTrue : valueIfFalse).
    • Iteration Statements (Loops)
    • Allow code blocks to run multiple times until a condition is met.
    • for loop: Has three parts: initialization, condition, and increment/decrement (e.g., for (let i = 0; i < 10; i++) { … }). Often used to iterate a fixed number of times or through arrays using length.
    • while loop: Continues to execute as long as a specified condition is true. More flexible, as the iteration control can be embedded within the loop’s body.
    • break: Exits a loop or switch statement immediately.
    • Objects
    • An object stores related properties (attributes) of a single data element.
    • Object Literal Syntax: Defined using curly braces {} with name: value pairs for properties and methods.
    • Properties: Named values that define characteristics (e.g., make: ‘BMW’).
    • Methods: Functions defined inside an object (e.g., printDescription: function() { … }).
    • Accessing Properties/Methods: Use dot notation (object.property) or bracket notation (object[‘property’]). Dot notation is generally preferred.
    • Objects can be dynamically modified (properties added/removed).
    • Can contain complex structures like nested objects or arrays of objects.
    • Related to JSON (JavaScript Object Notation), a common format for data exchange, with very similar but not identical syntax to object literals.
    • Arrays
    • A variable that can hold many different values (a list of information).
    • Declared using square brackets [] with comma-separated values (e.g., let a =).
    • Elements are zero-indexed (first element is at index 0).
    • Can hold elements of different data types within the same array.
    • length property: Returns the number of elements in the array (not zero-indexed).
    • Common Array Methods:
    • push(): Adds one or more elements to the end.
    • pop(): Removes the last element.
    • shift(): Removes the first element.
    • unshift(): Adds one or more elements to the beginning.
    • concat(): Combines two or more arrays.
    • join(): Joins all elements into a single string, with an optional separator.
    • reverse(): Reverses the order of elements.
    • sort(): Sorts the elements (lexicographically for strings, numerically for numbers).
    • indexOf(): Returns the first index at which a given element can be found.
    • lastIndexOf(): Returns the last index at which a given element can be found.
    • map(): Creates a new array by calling a function on every element of the original array.
    • filter(): Creates a new array with all elements that pass a test implemented by a provided function.
    • forEach(): Executes a provided function once for each array element.
    • every(): Checks if all elements in an array pass a test.
    • some(): Checks if at least one element in an array passes a test.
    • Error Handling
    • JavaScript’s runtime will throw an exception and quit if it encounters something it cannot work with.
    • try-catch-finally: A construct to safeguard code.
    • try: Contains code that might throw an exception.
    • catch: Executes if an exception is thrown in the try block, allowing you to handle the error (e.g., inspect the Error object’s message property).
    • finally: Executes regardless of whether an exception occurred or was caught, typically for cleanup.
    • Throwing Custom Errors: You can use throw new Error(“message”) to communicate failures from a function to its caller.
    • Advanced Topics (Introduced as Basics)
    • this Keyword: Represents the context in which a function is called, and its value depends on how the function is invoked (e.g., globally, as an object method, using call() or apply()). In a web browser, this can refer to the window object (global context) or the DOM element that triggered an event.
    • Destructuring: A syntax for “unpacking” values from arrays or properties from objects into distinct variables or other array/object elements.
    • Template Literals: Use backticks (`) to create strings that can span multiple lines and embed expressions using ${expression} (interpolation).
    • Regular Expressions (Regex): Patterns used to search, match, and manipulate strings. While complex, basic use involves creating patterns (/pattern/) and using string methods like test() (checks for match), replace() (replaces matches), and match() (returns match details).
    • Built-in Natives (Primitive Wrappers): Primitive types like string, number, and boolean have corresponding built-in “native” functions (e.g., String, Number, Boolean) that return objects with rich sets of methods. JavaScript automatically “boxes” (wraps) primitives into these objects when methods are called and “unboxes” them back to primitives.
    • Constructor Functions: Normal functions that, when called with the new keyword, create and initialize a new object instance. The new keyword binds the newly created empty object to this inside the constructor function. Constructor functions are conventionally named with an uppercase first letter.
    • Prototype Chain (Prototypal Inheritance): JavaScript’s mechanism for inheritance. Objects can link to other objects (prototypes), forming a chain. When a property or method is accessed on an object, JavaScript searches up this chain until it finds the definition.
    • Classes: Introduced in modern JavaScript as syntactic sugar over the existing object and prototype models. They provide a more familiar class-like syntax (class Car { constructor() {} method() {} }) but internally still rely on prototypes. They can extend other classes to approximate inheritance.
    • Closures: Allow a function to “remember” and access variables from its outer (lexical) environment even after the outer function has finished executing. Each closure creates its own “lexical environment”.
    • Truthy and Falsy Values: JavaScript evaluates certain values as true (truthy) or false (falsy) in a boolean context, even if they are not explicitly boolean. Examples of falsy values include false, null, undefined, 0, NaN, and empty strings (”, “”). Everything else is generally truthy.
    • JavaScript in Web Browsers (DOM)
    • The Document Object Model (DOM) is an object-based representation of an HTML page, allowing programmatic access and manipulation of elements, their attributes, and text.
    • Web browsers construct the DOM by parsing HTML, applying CSS styles, and processing JavaScript.
    • JavaScript can interact with the DOM to:
    • Access nodes: Using methods like document.getElementById().
    • Change attributes: Modify properties of DOM elements (e.g., element.style.fontSize).
    • Add/Remove nodes dynamically: Create new elements (document.createElement()) and append them (element.appendChild()) or remove them.
    • Associate event handlers: Attach functions to respond to user interactions (e.g., element.addEventListener(‘click’, function)).
    • It’s generally recommended to keep JavaScript in separate .js files and link them in the HTML using <script src=”file.js”></script> at the bottom of the <body> to ensure DOM elements are loaded before scripts try to access them. Inline JavaScript in HTML attributes (like onclick) or <script> tags in the <head> is generally frowned upon for professional development.

    JavaScript Variables and Scope Fundamentals

    In JavaScript, understanding variables and their scope is fundamental to writing effective and maintainable code.

    Variables

    A variable is essentially a named area in the computer’s memory where you can store and retrieve values throughout the lifespan of your application.

    JavaScript offers several keywords for declaring variables:

    • let: This is the recommended keyword for declaring variables in modern JavaScript. It allows you to express your intent to create a new variable.
    • var: This was the original keyword for variable declaration. Its usage can be nuanced and may lead to unexpected behaviors, particularly concerning scope, which can be challenging for beginners. It’s generally advised to abandon var unless specifically required.
    • const: This keyword is used when you intend for a variable’s value never to change after its initial assignment. Attempting to reassign a const variable will result in an error.

    Variable Assignment and Initialization: The equal sign (=) is the assignment operator, used to assign a value to a variable. When you declare a variable but do not immediately assign it a value, its value is undefined. This is known as declaration without definition. It’s generally preferable to initialize your variables at the moment of declaration if possible.

    Naming Rules for Variables (Identifiers): There are strict rules for naming variables (also called identifiers) that, if violated, will cause your application to break:

    • All identifiers must begin with a letter, a dollar sign ($), or an underscore (_).
    • Variable names can contain letters, numbers, dollar signs, or underscores, but no other special characters or spaces.
    • You cannot use JavaScript keywords as variable names (e.g., let cannot be a variable name).
    • Variable names are case-sensitive (e.g., x and X are treated as two different variables).

    Code Conventions for Variables (Best Practices): These are not enforced by the JavaScript compiler but are highly recommended for readability and collaboration:

    • Descriptive names: Use names that clearly indicate the purpose or meaning of the data being stored (e.g., firstNumber instead of x).
    • Camel casing: For multi-word variable names, the first word should be lowercase, and subsequent words should start with a capital letter (e.g., firstName, zipCode).
    • Consistency: Maintain a consistent naming style throughout your application.
    • Do not rely on case: Avoid using variable names that differ only by case if they refer to conceptually the same thing, as this can introduce subtle confusion and programming errors (e.g., zipCode and zipcode as distinct variables should be avoided).

    Data Types and Variables: It’s important to note that variables themselves do not have a data type; only the values stored inside the variables have a data type. Common data types include number, boolean, string, undefined, object, and function.

    Scope

    Scope refers to the lifespan and availability of variables and functions within your application. Variables are like people; they have a lifespan (born, do work, die) and a “citizenship” determining where they can be accessed. When a code block finishes executing, variables defined within that block are typically removed from the computer’s memory, meaning they go “out of scope”.

    Fundamental Rules of Scope:

    • A variable declared in an outer (parent) code block (scope) is visible and accessible within all inner (child) code blocks that it encloses.
    • Conversely, a variable declared in an inner (child) code block is not available to outer (parent) scopes once that inner block has finished executing.
    • Variables declared in an outer scope can have their values changed by code within inner scopes.

    Global Scope: The global scope is the topmost level of scope in JavaScript. While less of an issue in Node.js applications, defining variables and functions in the global scope is a crucial concern and generally considered a bad idea in web development:

    • Memory Consumption: Each variable defined in the global scope remains in the computer’s memory until the web browser tab navigates to a new page, potentially consuming significant memory over time.
    • Naming Collisions: When multiple JavaScript files (your code, libraries, third-party scripts) are loaded on a single web page, defining variables and functions in the global scope increases the likelihood of “naming collisions.” This occurs when two different scripts define variables or functions with the same name, leading to one overwriting the other, causing unanticipated and difficult-to-track bugs.
    • The var keyword, unlike let or const, specifically attaches variables to the global scope (e.g., the window object in a web browser’s Document Object Model, or DOM). Therefore, let is recommended to avoid polluting the global scope.

    Solutions to Global Scope Issues (Module Pattern): To mitigate global scope problems, especially in web development, the Module Pattern is a widely used design pattern. This technique employs an Immediately Invoked Function Expression (IIFE) that returns an object.

    • It allows you to define private variables and functions that are not directly accessible from outside the module, promoting encapsulation (hiding implementation details).
    • The IIFE then returns an object containing “public” properties and methods, which are the only parts exposed to the outside world.
    • This significantly reduces the impact on the global scope by consolidating many internal variables and functions under a single, unique module variable.
    • The Revealing Module Pattern is a variation that explicitly lists the public properties and methods within the returned object, offering a cleaner presentation of what is exposed.

    Closures (A Related Concept): Closures are a powerful JavaScript concept related to scope. A closure allows a function to remember and access variables from its surrounding lexical environment (the scope in which it was declared), even after that outer function has finished executing.

    • Essentially, it associates some data with a function at the time the function is created.
    • Each closure creates its own lexical environment, meaning it gets its own set of variables and input parameters from its enclosing scope. This allows for functions that are “pre-filled” with certain data based on when and where they were defined and returned.

    The this Keyword (Contextual Binding): The meaning of the this keyword in JavaScript is not fixed; it represents the way a given function is called, and its value changes based on the context of that call.

    • Global Context: When a function is called directly in the global scope (not as a method of an object or with explicit binding), this refers to the global object (e.g., global in Node.js, or window in a web browser).
    • Strict Mode: If “use strict” is enabled, calling a function in the global context will cause this to be undefined instead of the global object.
    • Object Methods: When a function is invoked as a method of an object (e.g., myObject.myMethod()), this inside that method refers to the object itself (myObject in this example). This allows methods to access the object’s properties (e.g., this.propertyName).
    • Explicit Binding (call() and apply() methods): Functions in JavaScript have built-in methods, call() and apply(), that allow you to explicitly set the value of this for that function call. The difference between call() and apply() lies in how additional arguments are passed: call() takes them individually, while apply() takes them as an array.
    • DOM Event Handlers: In web browsers, when a function is called from an inline event handler (e.g., onclick=”myFunction(this)”), the this passed as an argument within the HTML refers to the DOM element itself. However, if the handler function itself is defined without explicit binding, the this inside that function will default to the global window object.

    Understanding variables and how their scope impacts their availability and behavior is crucial for developing robust JavaScript applications.

    JavaScript: Functions, Objects, and Their Interrelation

    In JavaScript, functions and objects are core building blocks for structuring and organizing code. They work together to create dynamic and interactive applications.

    Functions

    A function is a named block of code that can be repeatedly executed throughout your application. Functions serve as a primary construct in JavaScript for accomplishing tasks.

    Function Declaration vs. Function Expression:

    • A function declaration uses the function keyword followed by a name (identifier). For example, function sayHello() { … }. Function declarations are “hoisted” to the top of their execution environment, meaning they can be called before they are defined in the code.
    • A function expression is typically an anonymous function (without a name) assigned to a variable. For example, let myFunc = function() { … }. These are often used when a function is needed as an argument to another function or when it’s only called once.

    Arrow Functions:

    • Introduced in recent JavaScript versions, arrow functions (=>) provide a shorthand syntax for defining functions. They remove the need for the function keyword and use a “fat arrow” to point to the function body.
    • They can accept input parameters within parentheses and have a body defined by curly braces.
    • Arrow functions are especially useful for concise, inline functions, such as when iterating over arrays with methods like map(), filter(), or forEach().

    Key Aspects of Functions:

    • Arguments (Input Parameters): Functions can accept data (arguments) passed into them, which can then be used within the function’s body.
    • Return Values: Functions can return a single value back to wherever they were called using the return keyword. This value can be any data type, including another function.
    • Functions as Data Types: In JavaScript, functions are considered a data type themselves. This means they can be assigned to variables, passed as arguments to other functions, and even returned as values from other functions.
    • Immediately Invoked Function Expressions (IIFEs): An IIFE is a function expression that is executed immediately after it’s defined. It’s typically wrapped in parentheses and then followed by another set of parentheses to invoke it. IIFEs are a common pattern in JavaScript development, particularly for controlling scope and avoiding global variable pollution.

    Objects

    An object is a container that holds related properties and methods (functions) of a single data element. Unlike arrays, which hold lists of multiple data elements, an object defines the characteristics and behaviors of one specific item.

    Creating Objects:

    • Object Literal Syntax: This is the most common way to create an object, using curly braces {} to define a collection of name-value pairs (properties) and functions (methods). For example, let car = { make: “BMW”, model: “745li”, year: 2010 };.
    • Constructor Functions: A constructor function is a regular JavaScript function that is intended to be called with the new keyword. The new keyword creates an empty object, sets it as the this context for the function call, and then the function populates this new object with properties and methods. A convention is to name constructor functions with an uppercase first letter to indicate their intended use with new.
    • Classes (ES6): Introduced as “syntactic sugar” in the latest JavaScript versions, class provides a more familiar structure for defining objects, resembling traditional object-oriented programming (OOP) languages like Java or C#.
    • A class can have a special constructor method that is automatically called when a new instance of the class is created using new.
    • Methods can be defined directly within the class body.
    • The extends keyword allows a class to “inherit” from another class, providing properties and methods from the parent class to the child class. Despite the class and extends keywords, JavaScript still operates on its underlying prototype model for “inheritance”.

    Key Aspects of Objects:

    • Properties and Methods: Properties are named values that describe the object (e.g., car.make), while methods are functions associated with the object that define its behavior (e.g., car.printDescription()).
    • Accessing Members: Properties and methods are typically accessed using dot notation (.) (e.g., car.make, car.printDescription()). Bracket notation (car[‘make’]) can also be used, though dot notation is generally preferred.
    • Dynamic Nature: Objects in JavaScript are dynamic; properties and methods can be added or even deleted from an object after it has been created.
    • Object Graphs: Objects can contain other objects or arrays of objects, forming complex data structures known as “object graphs”.
    • JSON (JavaScript Object Notation): JSON shares a very similar syntax with JavaScript object literals, making it a popular format for data interchange between systems.

    Interrelation and Key Concepts

    Functions and objects are deeply intertwined in JavaScript:

    • The this Keyword: This is a crucial concept, as this represents the context in which a function is called, and its value changes dynamically.
    • When called in the global context, this refers to the global object (e.g., window in browsers, global in Node.js).
    • When a function is invoked as a method of an object (e.g., myObject.myMethod()), this inside that method refers to the object itself (myObject). This allows methods to access the object’s properties (e.g., this.propertyName).
    • The call() and apply() methods allow you to explicitly set the value of this for a function call.
    • In DOM event handlers, this typically refers to the DOM element on which the event listener is defined.
    • Scope and Module Pattern: Functions are fundamental to controlling variable scope. The Module Pattern, which often utilizes an IIFE that returns an object, is a widely used design pattern to encapsulate private variables and functions and expose only “public” ones through a single object, thereby reducing global scope pollution and naming collisions.
    • Closures: Closures are a powerful feature where a function “remembers” and can access variables from its surrounding (lexical) environment even after the outer function has finished executing. This allows a function to be pre-filled with specific data from its creation context.
    • Built-in Natives: JavaScript’s primitive data types (like string, number, boolean) have corresponding “built-in native” constructor functions (e.g., String(), Number()) that return objects. The JavaScript compiler automatically “boxes” primitives into these native objects to provide them with a rich set of methods (e.g., string.toLowerCase()), and “unboxes” them back as needed. Arrays and regular expressions are also built-in natives that are objects and come with their own sets of methods.

    JavaScript Control Flow: Logic, Loops, and Error Handling

    In JavaScript, control flow refers to the order in which individual statements, instructions, or function calls are executed. By default, JavaScript statements execute sequentially from top to bottom within a file. However, various constructs allow developers to alter this default sequential execution, introducing logic, repetition, and error handling into their applications.

    Basic Building Blocks of Code

    • Statements: A statement is one complete instruction to the JavaScript compiler, similar to a sentence in English. Each JavaScript file typically contains one or more statements that usually execute in sequential order.
    • Expressions: Statements are composed of one or more expressions, which are in turn made up of operators and operands. Operators are keywords or symbols (like +, =, let), while operands are values or identifiers (like variable names or function calls). Combining operators and operands creates expressions that perform actions or evaluations.

    Categories of Control Flow

    JavaScript provides several categories of control flow mechanisms:

    1. Sequential Execution By default, JavaScript code runs from the first line to the last line. This is the simplest form of control flow.
    2. Decision Statements Decision statements allow you to perform different blocks of code based on whether a certain condition evaluates to true or false. JavaScript treats certain values as “truthy” (evaluating to true) or “falsy” (evaluating to false) even if they are not explicitly true or false booleans. For example, null, undefined, 0, NaN, and empty strings (“”, ”) are considered falsy, while an empty object ({}), an empty array ([]), non-empty strings, and any non-zero number are truthy.
    • if / else if / else: This is the most common decision statement.
    • An if statement evaluates an expression; if it’s true, the code block associated with it is executed.
    • You can include optional else if statements to evaluate other expressions if the preceding if or else if conditions were false.
    • An else statement acts as a catch-all, executing its code block if none of the preceding if or else if conditions were true.
    • switch Statement: The switch statement evaluates a single expression against a number of case values.
    • If a case matches the expression’s value, the code block under that case is executed.
    • Without a break statement, execution will “flow through” to subsequent case blocks, including the default case if present. The break statement is used to exit the switch block after a match is found.
    • A default case can be provided to handle situations where none of the case values match.
    • Ternary Operator (? 🙂: This provides a concise, inline way to perform a quick evaluation and return one of two values.
    • It consists of an expression, followed by a question mark (?), then the value to return if the expression is true, a colon (:), and finally the value to return if the expression is false.
    • For example, doesAEqualB ? “equal” : “not equal”.
    • Equality Operators: The source discusses both loose equality (==) and strict equality (===). Loose equality performs type coercion before comparison (e.g., 7 == “7” is true), while strict equality checks both value and data type without coercion (e.g., 7 === “7” is false). Similar operators exist for inequality (!= and !==).
    1. Iteration Statements (Loops) Iteration statements allow a block of code to be executed repeatedly until a specified condition is met.
    • for Loop: A for loop is typically used when you know the number of iterations or want to iterate over a sequence using an index. It has three parts:
    • Initialization: Declares and initializes a counter variable (e.g., let i = 0).
    • Condition: An expression that is evaluated before each iteration; the loop continues as long as this condition is true (e.g., i < 10).
    • Increment/Decrement: An operation performed after each iteration to update the counter (e.g., i++).
    • for loops are often used to iterate through arrays, accessing elements by their index.
    • while Loop: A while loop continues to execute its code block as long as a given condition remains true.
    • It is more flexible than a for loop because the iteration logic (like incrementing a counter or reading to the end of a file) is controlled within the loop’s body, not just in its header.
    • The break statement can be used within both for and while loops to immediately exit the loop, regardless of the loop’s condition.
    1. Error Handling JavaScript applications can encounter “exceptions” or “errors,” which are situations that prevent the code from continuing execution. When an exception occurs, the JavaScript runtime will “quit” at that point, stopping any further code execution.
    • try-catch-finally: This construct allows you to safeguard code that might throw an exception.
    • The try block contains the code that is susceptible to throwing an exception.
    • If an exception occurs within the try block, execution immediately jumps to the catch block, which receives an “error object” containing information about the exception (e.g., error.message). This prevents the application from completely shutting down.
    • The finally block will execute regardless of whether an exception occurred or was caught. It’s often used for cleanup operations.
    • Throwing Custom Exceptions: Developers can explicitly throw a new Error object from their functions to communicate failure to the caller. This allows the calling code to implement contingency or retry logic.

    JavaScript Data Types and Coercion

    In JavaScript, data types are essentially a description of the kind of data you want to store and what you intend to do with it. Unlike some other programming languages, variables themselves do not have a data type; only the values stored inside the variables have data types.

    JavaScript categorizes its data types into several fundamental types:

    Primitive Data Types

    The core primitive data types discussed include:

    • Number: Used for any positive or negative numbers, including decimal values. If you want to perform math or algebraic operations, you should use a number.
    • Boolean: Represents true or false values. These are the only two possible values for a boolean.
    • String: Represents a sequence of characters. Strings are typically enclosed in single quotes (”) or double quotes (“”). They are often used to display content on the screen.
    • Undefined: This type indicates that a variable has been declared but no value has been assigned or initialized to it. When a variable is undefined, its value is undefined, and its type is also undefined. It’s different from null because undefined implies an expected value was never set, whereas null means an object reference was expected but is currently pointing to nothing.
    • Null: Represents a variable that points to nothing, specifically when an object reference was expected. While its value is null, a known quirk in JavaScript is that typeof null returns “object”, not “null”. This is a known bug that is unlikely to be fixed due to existing code dependencies. It is not zero, undefined, or an empty string.

    Other Data Types

    • Object: This is a more complex data type. An object contains the related properties (attributes) and methods of a single data element, contrasting with an array which holds a list of many data items. Arrays themselves are considered a type of object (typeof an array returns “object”). Objects can hold properties of various data types, including other objects or arrays.
    • Function: Functions are considered their own data type in JavaScript. A reference to a function, when its invocation operator () is not used, will reveal its type as function.

    The typeof Operator

    The typeof operator can be used to determine the data type of a value. For example, typeof x will output the data type of the value currently stored in x.

    Type Coercion

    JavaScript can sometimes automatically convert one data type into another in certain operations, a process known as coercion. This can lead to unexpected results.

    • For instance, the plus operator (+) performs double duty: it can be the addition operator for numbers or the string concatenation operator for strings.
    • If you attempt to “add” a number and a string (e.g., 7 + “6”), JavaScript will coerce the numeric value into a string and then concatenate the two strings (resulting in “76”).
    • To force a string to be treated as a number for arithmetic operations, you can use built-in functions like parseInt(). parseInt() takes a string and an optional radix (base system, e.g., 10 for decimal) to convert the string into an integer.
    • If a string cannot be converted into a numeric value, parseInt() (or other numeric conversion attempts) might return NaN (Not a Number), which is a special numeric value indicating an invalid or unrepresentable number.

    Primitive Types and Built-in Natives

    JavaScript provides “built-in native” functions (or constructors) for primitive types like String, Number, and Boolean, distinguished by their uppercase first letter.

    • These native functions return objects that provide a rich set of methods and properties (e.g., value.replace() for strings, string.toLowerCase(), string.length).
    • When you use a primitive value (like a literal string “howdy”) and call a method on it (e.g., “howdy”.toLowerCase()), the JavaScript compiler coerces or “boxes” that primitive into its corresponding built-in native object behind the scenes to provide the method, and then “unboxes” it back into a primitive when needed, without explicit developer intervention.
    • You can explicitly create instances of these native objects using the new keyword (e.g., new String(“howdy”)), and then use the .valueOf() method to convert them back into their primitive equivalents. However, it is generally recommended to stick with using the primitive types and let JavaScript handle the boxing and unboxing automatically.

    Truthiness and Falsiness

    In decision statements (like if or switch), JavaScript evaluates expressions to determine if they are “truthy” or “falsy”.

    • Falsy values are those that, when evaluated in a boolean context, are treated as false:
    • false
    • null
    • undefined
    • 0 (the number zero)
    • NaN (Not a Number)
    • “” or ” (empty strings)
    • Truthy values are all other values that are not explicitly falsy, meaning they evaluate to true in a boolean context:
    • true
    • Empty objects ({})
    • Empty arrays ([])
    • Non-empty strings
    • Any non-zero number (integers or floats)
    • Infinity (positive or negative)
    Javascript tutorial for beginners Full course | javascript Full crash course for Beginners

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • Mastering Visual Basic: Building Applications from Scratch by Bob Tabor

    Mastering Visual Basic: Building Applications from Scratch by Bob Tabor

    The provided texts introduce Visual Basic programming, emphasizing practical application development for various platforms. They commence by guiding users through Visual Studio 2015 installation, particularly the custom setup to include essential programming languages like Visual C++, F#, Python tools, and development kits for Universal Windows Platform and cross-platform mobile development using Xamarin. The content then transitions into fundamental Visual Basic syntax, explaining code structure, variables (integers, strings), data types, operators, and conditional logic using if/else statements. It also covers iteration statements like For/Next and While/Do While loops, along with arrays, string manipulation, and the creation of custom methods (subroutines and functions), including overloaded methods and passing parameters by value (ByVal) versus by reference (ByRef).

    Visual Basic: A Programming Foundation

    Visual Basic is a programming language designed to introduce absolute beginners to programming and building applications on the Windows platform. It aims to make programming concepts understandable and accessible.

    Here’s a comprehensive discussion of Visual Basic based on the sources:

    What is Visual Basic?

    • Purpose and Target AudienceVisual Basic (VB) is ideal for individuals completely new to programming, the VB language, and developing on the Windows platform. It emphasizes not just “what” to do, but “why” and the thought process behind it.
    • It’s used to build .NET applications.
    • The course explicitly states that this flavor of Visual Basic is not for creating macros in Excel or other Microsoft Office tools; that functionality is provided by Visual Basic for Applications (VBA). While VB and VBA may look similar, their capabilities are “extremely different”.
    • Readability and VerbosityVisual Basic is described as a “more human readable programming language” compared to others.
    • However, this readability “comes at a price”: it’s more verbose, meaning you have to use more keystrokes to build code instructions than languages like C#.
    • Despite this, there’s “virtually no difference” between applications created using C# and those created with Visual Basic because both compile into a .NET assembly.
    • Many fundamental programming concepts learned in Visual Basic transfer almost directly to C#.
    • Evolution and HistoryThe instructor, Bob Tabor, has taught Visual Basic to hundreds of thousands of people for over 14 years, including children as young as 8 and adults as old as 80.
    • The course itself is the sixth iteration, dating back to 2005, with feedback from thousands of students incorporated over the years.
    • Visual Basic holds a “special place” for the instructor as they learned the BASIC programming language at 12 years old. BASIC stands for “Beginners All-Purpose Symbolic Instruction Code”.
    • Visual Basic was one of the first applications that allowed users to visually design forms by dragging and dropping components from a toolbox onto a form designer.
    • Application ScopeAfter learning the basics, you can build a wide range of applications using Visual Basic, including web applications, Windows Store applications, cloud services, video games, and even applications for iOS and Android.

    Key Tools: Visual Studio and the .NET Framework

    • Visual StudioVisual Studio is the Integrated Development Environment (IDE) where you write Visual Basic code.
    • The course assumes you have some version and edition of Visual Studio installed. The instructor uses Visual Studio 2015 Community Edition (a free version), but any edition or version is compatible, though minor user interface differences might exist.
    • Installation: Visual Studio can be downloaded from visualstudio.com. It’s recommended to choose the “Custom” installation option to ensure all necessary packages and libraries for your desired application types (e.g., universal Windows apps, cross-platform mobile development with Xamarin) are installed.
    • Project and Solution Structure:
    • Visual Basic code files are organized into projects, and one or more projects are organized into solutions.
    • A project (e.g., Hello World.vbproj) typically contains code files (e.g., Module1.vb), boilerplate code, and settings.
    • A solution (e.g., Example.sln) acts as an umbrella that owns projects, especially useful for complex applications with multiple related projects.
    • By default, projects are stored in your user’s Documents\Visual Studio\[Version]\Projects subdirectory, but they can be saved anywhere.
    • Projects are compiled into a single .NET assembly (an executable file or library).
    • Developer Tools within Visual Studio:
    • Solution Explorer: This window is your main navigational device for files and settings within your project and solution.
    • Code Editor: The main area where you type your Visual Basic code.
    • Intellisense: Provides helpful pop-up information and messages as you type, guiding you with available methods, properties, and parameters.
    • Error List: Displays compilation errors with hints and clues as to where problems exist in your code, often accompanied by red squiggly lines in the editor.
    • Debugging Tools: Visual Studio offers powerful debugging features to pause and watch the execution of code.
    • Breakpoints (red circles/octagons in the margin) can be set to stop program execution at specific lines.
    • You can step through code line by line (Step Over/F10) to observe variable values.
    • Watch windows (Autos, Locals, Watch) allow you to monitor variable values as they change.
    • Conditional breakpoints can be configured to stop execution only when specific conditions are met (e.g., an index equals 7).
    • Code Snippets: Shortcuts to generate common code blocks (e.g., typing for tab tab expands into a For Next loop template, if tab tab for an If statement).
    • .NET FrameworkThe .NET Framework is a collection of pre-built functionality created by Microsoft that developers can use in their applications.
    • It consists of two primary parts that concern beginners:
    • Class Library: A vast library of pre-written code that handles complex tasks like math operations, text manipulation, displaying things to the screen, or network communication. Developers can “borrow” or “use” this code rather than building it from scratch. Examples include the Console class and the Random class.
    • Runtime (Common Language Runtime or CLR): This acts as a “protective bubble” where your application runs. It manages low-level details such as interacting with the computer’s operating system, memory, and hardware. It also provides a layer of protection for the end-user against malicious software. The CLR is responsible for allocating memory space for variables based on their declared data types.

    Fundamental Visual Basic Programming Concepts

    • Code Precision and ReadabilityWriting Visual Basic code is an exercise in preciseness. You must type code exactly as intended, including spelling and punctuation. Even minor deviations can prevent compilation or lead to errors.
    • Visual Basic is considered a “forgiving” language because it often provides hints (red squiggly lines, error list) to guide you to problems.
    • Indentation, white space, and color coding in Visual Studio enhance code readability, making it easier to understand the structure and hierarchy.
    • You can use a single quote (‘) to add comments to your code, which are ignored by the compiler.
    • A line continuation character (_) allows you to split long lines of code onto multiple physical lines for better readability without affecting execution.
    • Statements, Expressions, Operators, and OperandsStatements are complete instructions or “thoughts” in Visual Basic, analogous to sentences in English.
    • Expressions are components of statements, often evaluating to a value (e.g., userValue = 1, Console.WriteLine(“Hello World”)).
    • Operands are like nouns, representing “things” such as variables, literal strings, or literal numbers (e.g., x, “Hello World”, 7).
    • Operators are like verbs, performing actions on operands. Visual Basic has many built-in operators.
    • Assignment Operator (=): Used to set the value of a variable (e.g., x = 7).
    • Arithmetic Operators (+, -, *, /): Standard mathematical operations.
    • Equality Operator (=): Used in conditions to check if two values are equal (e.g., userValue = 1 in an If statement).
    • Comparison Operators (>, <, >=, <=): Used for numerical or alphabetical comparisons.
    • String Concatenation Operator (&): Used to append or tie together strings (e.g., “Hello ” & myFirstName).
    • Compound Assignment Operators (+=, -=, &=): Shortcuts for combining an operation with assignment (e.g., guesses += 1 is equivalent to guesses = guesses + 1).
    • Member Access Operator (.): Used to access members (properties or methods) of an object or class (e.g., Console.WriteLine).
    • Method Invocation Operator (()): Parentheses after a word indicate that a method is being called or invoked. They can contain input parameters.
    • Variables and Data TypesA variable is conceptually a “bucket in your computer’s memory” that can hold a value. Values can be stored, retrieved, or overwritten in variables.
    • You declare a variable using the Dim keyword (short for “dimension”) and must specify its data type using As [DataType] to tell the .NET runtime how much memory to allocate (the “size of the bucket”).
    • Key Data Types Covered:
    • Integer: For whole numbers without decimal points, ranging from approximately -2 billion to +2 billion.
    • String: For sequences of characters (text).
    • Boolean: For true/false values.
    • Date: For storing dates and times.
    • TimeSpan: For representing a duration or span of time between two dates.
    • Decimal: For monetary values, allowing precision after the decimal point.
    • Initialization: It’s good practice to initialize variables by setting their value immediately upon declaration, putting them into a “valid state”.
    • Case Insensitivity: Visual Basic is case-insensitive, meaning myfirstname and MyFirstName refer to the same variable. You cannot declare two variables with the same name, even if their casing differs.
    • Type Conversion: You can convert values between data types using functions like CInt() (convert to Integer) or CStr() (convert to String), or methods like .ToString().
    • Input and OutputConsole.WriteLine(): Displays a line of text to the console window and then moves the cursor to the next line.
    • Console.Write(): Displays text but keeps the cursor on the same line, allowing user input to appear immediately after the prompt.
    • Console.ReadLine(): Used to pause the application and wait for the user to press Enter. It can also capture and return the text typed by the user before they press Enter.
    • Console.Clear(): Clears all text currently displayed in the console window.

    Control Flow: Decisions and Iterations

    • Decisions (Conditional Logic)If…Else If…Else…End If: This structure allows your application to execute different blocks of code based on whether a given condition is True or False.
    • A simplified If statement can use the Then keyword to put a simple check and its result on a single line.
    • The IIf() function is a compact way to perform a conditional evaluation and return one of two values based on the result.
    • Iterations (Loops)For Next: Used to execute a block of code a preset number of times. It typically uses an index variable that iterates from a starting value to an ending value. You can use Exit For to prematurely break out of the loop. The Step keyword allows the index to increment by a value other than one (e.g., Step -1 for backward iteration, Step 2 to count by twos).
    • For Each: Provides an elegant way to iterate through each item in an array or collection, without needing to manage indexes or lengths explicitly. It temporarily copies the current item’s value into a variable for use within the loop.
    • While…End While: This loop repeatedly executes a block of code as long as a specified condition remains True. The condition is checked before each iteration, so the code block might not run at all if the condition is initially False. This is useful when the number of iterations is not known in advance.
    • Do While: Similar to While, but it guarantees that the code block will execute at least one time before the condition is checked. The condition is evaluated at the end of the loop body.

    Data Manipulation

    • ArraysAn array is a way to work with several related values of the same data type, treated as a single unit or “bucket” containing smaller “sub-buckets”.
    • Arrays are zero-based, meaning the first element is at index 0. When declaring, the number in parentheses specifies the highest index, so Dim numbers(4) As Integer creates an array with 5 elements (0 through 4).
    • Individual elements are accessed using their index in parentheses (e.g., numbers(0)).
    • The .Length property can be used to determine the total number of items in an array.
    • Attempting to access an array element outside its defined range will result in an IndexOutOfRangeException at runtime.
    • Arrays can be initialized directly with values when declared, allowing the compiler to determine the size based on the provided values (e.g., Dim numbers() As Integer = {4, 8, 15}).
    • A String is internally treated as an array of individual characters.
    • The String.ToCharArray() method can convert a string into an array of characters.
    • The Array.Reverse() method can be used to reverse the order of elements in an array.
    • The String.Concat() method can combine elements of a character array back into a single string.
    • String ManipulationVisual Basic and the .NET Framework offer extensive functionality for manipulating strings.
    • Special Characters: To include a literal double quote within a string, use two double quotes (“”) together (e.g., myString = “my “”so-called”” life”). You can insert new lines using vbNewLine and tabs using vbTab constants.
    • Formatting with String.Format(): This method allows you to create formatted strings using replacement syntax ({0}, {1}, etc.) within a template string. It also supports custom format codes (e.g., {0:C} for currency, {0:N} for numbers with commas, {0:P} for percentages, or custom patterns like ###-###-#### for phone numbers).
    • Common String Methods:
    • .Substring(): Extracts a portion of a string.
    • .ToUpper() / .ToLower(): Converts the entire string to uppercase or lowercase.
    • .Replace(): Substitutes occurrences of specified characters or substrings with others.
    • .Length: Returns the number of characters in the string.
    • .Trim() / .TrimStart() / .TrimEnd(): Removes leading and/or trailing whitespace characters.
    • String Immutability and StringBuilder: Strings are immutable in Visual Basic. This means that every time you modify a string (e.g., append characters), a new string object is created in memory, which can be inefficient for frequent modifications. For extensive string appending, the StringBuilder class is more memory-friendly as it allows mutable string operations. It requires importing the System.Text namespace.
    • Date and Time ManipulationThe Date data type is used to work with specific points in time. Its default value is January 1st, 1 AD at midnight.
    • The Now function provides the current date and time.
    • Formatting Dates and Times: The Date type has built-in methods like ToLongDateString(), ToShortDateString(), ToLongTimeString(), and ToShortTimeString() to display dates and times in various common formats based on the computer’s regional settings. You can also use the .ToString() method with custom format strings (e.g., MMMM for full month name, hh for 12-hour clock) for highly specific formatting.
    • Date Math: You can add or subtract units of time (days, hours, minutes, months, years) using methods like AddDays(), AddHours(), etc. To subtract, pass a negative number to these methods.
    • Initializing Dates: You can create Date objects for specific past or future dates using a constructor (e.g., New Date(year, month, day)) or by parsing a string representation of a date (Date.Parse(“string date”)). Literal dates can also be expressed by enclosing the date in pound symbols (#) (e.g., #12/7/1969#).
    • TimeSpan: The TimeSpan data type represents a duration of time. You can calculate a TimeSpan by subtracting one Date from another (e.g., Date.Now.Subtract(myBirthdate)) and then access total days, hours, or minutes within that span. You can also add TimeSpan values to dates or other TimeSpan values.
    • Just like with strings, it’s recommended to explore the many built-in functions for date and time manipulation rather than writing complex custom code.

    Object-Oriented Programming (OOP): Classes and Methods

    • The Conceptual Jump to ClassesWhile modules serve as containers for methods, classes have a special purpose related to Object-Oriented Programming (OOP). OOP can be a conceptual hurdle for new developers, but it’s crucial for building larger, more maintainable applications.
    • A class is a blueprint, pattern, or cookie cutter that defines the structure and behavior of a specific type of data or entity (e.g., a “Car” class defining what a car is in your application).
    • An object is an instance of a class created in the computer’s memory based on that blueprint (e.g., “myCar” is an object, an actual instance of the “Car” class). Each object is distinct and separate from other instances of the same class.
    • Every class implicitly inherits from System.Object in the .NET Framework, providing some basic functionality by default (e.g., ToString(), GetType()).
    • Defining Classes and PropertiesYou define a class using Public Class [ClassName] … End Class syntax, typically in a separate .vb file (e.g., Car.vb).
    • Properties define the attributes or characteristics of a class (e.g., Make, Model, Year, Color for a Car class). These are typically defined using Public Property [PropertyName] As [DataType]. This is a shorthand for an “auto-implemented property”.
    • Properties also have longer, “full-blown” versions with explicit Get and Set sections, allowing you to add custom logic like data validation or access control when a property’s value is retrieved or set.
    • Working with Objects (Instantiating Classes)You create an object (an instance of a class) using the New keyword (e.g., Dim myCar As New Car()). This New keyword acts like a “factory” that takes the class blueprint and creates a living object in memory.
    • Once an object is created, you can access its properties (to set or retrieve values) and call its methods using the member access operator (.) (e.g., myCar.Make = “Toyota”, Console.WriteLine(myCar.Year)).
    • Objects remain in memory as long as they are being used. When no longer referenced, they are eventually removed by the .NET runtime, freeing up memory.
    • Defining and Calling MethodsMethods are blocks of code defined within a class (or module) that perform specific actions. They help organize code, eliminate duplication, encapsulate functionality, and simplify maintenance.
    • Subroutines (Sub [Name](Parameters) … End Sub): These methods execute a block of code but do not return a value to the caller. They are “fire and forget”.
    • Functions (Function [Name](Parameters) As [ReturnType] … End Function): These methods execute a block of code and return a value of a specified data type to the caller.
    • Input Parameters: Methods can accept input parameters, which are values passed into the method to influence its behavior. Parameters are defined with a name and a data type, separated by commas.
    • Overloaded Methods: You can create multiple versions of methods with the same name, as long as they have different method signatures. A method’s signature is determined by the number and data types of its input parameters (parameter names do not affect the signature). Visual Studio’s Intellisense helps identify overloaded versions.
    • Passing Parameters by Value vs. by Reference:
    • ByVal (By Value): This is the default way parameters are passed. A copy of the variable’s value is sent to the method, so any changes made to the parameter within the method do not affect the original variable in the calling code.
    • ByRef (By Reference): When a parameter is passed ByRef, a reference to the original variable’s memory location is given to the method. This allows the method to directly manipulate the original variable in the calling code.
    • Code Readability and Strategy: It’s a best practice to strive for “human readable” code, making it “read as much like an English story as possible” by choosing good names for variables and methods. A general rule of thumb is to keep methods small, ideally no more than six lines of code, to maintain tidiness and readability.

    This foundational understanding provides a strong base for learning and developing with Visual Basic.

    Visual Studio: A Developer’s Essential Toolkit

    Visual Studio is an integrated development environment (IDE) that serves as a primary tool for developing applications using Visual Basic and other programming languages on the Windows platform. It provides a comprehensive environment for writing, testing, and managing code.

    Here’s a detailed discussion of Visual Studio based on the sources:

    What is Visual Studio?

    • Visual Studio is specifically designed for building applications on the Windows platform.
    • It functions as the code editor where you type your lines of code.
    • The course assumes you have some version and edition of Visual Studio installed on your local computer to begin writing code.
    • While the course focuses on the fundamentals of the Visual Basic language itself, Visual Studio is the primary tool used for demonstrations and exercises.

    Obtaining and Installing Visual Studio

    • You can visit visualstudio.com to learn about and download various free and commercial versions.
    • The instructor personally uses the Visual Studio 2015 Community Edition, which is a free version, for the course and his own work.
    • It is a web installer that initiates the installation routine upon running.
    • A custom installation option is highly recommended during setup to ensure you get all the necessary packages and libraries for the types of applications you wish to create.
    • By default, Visual Studio Community Edition installs C# and Visual Basic templates.
    • Through custom installation, you can add other programming languages like Visual C++, Visual F#, and Python tools.
    • You can also select components for Windows and web development, such as ClickOnce publishing tools, SQL Server data tools, PowerShell tools, and Silverlight development.
    • For developing Universal Windows Applications, the Universal Windows App Development Toolkit (including tools, emulators, and SDK) is crucial and easier to install during the initial setup.
    • Cross-platform mobile development tools (Xamarin platform) are available for creating applications for Windows Phone, iOS, and Android using C# within Visual Studio, and these include necessary emulators.
    • Installing all options can significantly increase the install size, potentially requiring up to 48 gigabytes across all drives.

    Using Visual Studio for Development

    • Project and Solution Management:
    • When you create a new project (e.g., through File > New Project or the Start page’s “New Project” link), Visual Studio automatically opens relevant files, like Module1.vb, based on the chosen project template.
    • Project templates provide a starting point with boilerplate code and settings.
    • Files and settings are organized into projects, which are then compiled into a single .NET assembly.
    • One or more projects are organized into solutions.
    • The Solution Explorer (typically in the upper right) provides a tree-like view of project items and is the main navigational device for files and settings. You can double-click a file in Solution Explorer to open it in the main area.
    • Projects are saved by default in your user’s Documents\Visual Studio\[Year]\Projects folder.
    • Solution (.sln) and project (.vbproj) files are typically XML files for settings and should not be manually edited.
    • The bin directory within a project folder contains the compiled executable output (binary) after compilation.
    • Code Editing and Navigation:
    • The main area is where you type code, typically shown as a tabbed area like Module1.vb.
    • IntelliSense provides helpful pop-up windows with information and messages as you type, indicating expected input parameters and showing overloaded method versions.
    • Visual Studio assists with code formatting by providing default indentation levels to denote containment and improve readability, although indentation is optional for execution.
    • Color coding different types of instructions (e.g., literal strings in deep red, classes/modules in aqua, keywords in royal blue, comments in green) also enhances readability.
    • White space does not affect program execution but improves readability.
    • Running and Debugging:
    • The “Start” button (green arrow) on the toolbar or the Debug menu’s “Start Debugging” option runs the application.
    • When running, Visual Studio’s appearance changes, and a console window typically pops up.
    • You can stop the application by clicking the ‘x’ button on the console window or pressing the Enter key.
    • Error Handling: Visual Studio helps identify problems with red squiggly lines under problematic code and displays a list of errors in the Error List window if compilation fails. Hovering over a red squiggly line often provides vague explanations but indicates the problem area.
    • Debugging Tools are a key feature:
    • You can set breakpoints (represented by a circle in the gray column next to a line number) to pause code execution.
    • While paused, you can hover your mouse cursor over variables to see their current values.
    • The “Continue” button resumes execution, while “Step Over” (F10) allows you to execute code line by line.
    • The Autos, Locals, and Watch windows display variable values, with values turning red when they change. You can also “pin” variable values to keep them visible.
    • Conditional breakpoints can be configured to stop execution only when a specific condition is met (e.g., index = 7), or to log messages without stopping.
    • Breakpoints can be temporarily disabled or entirely removed.
    • Productivity Features:
    • Code snippets allow you to type a keyword (e.g., for, if) and then press Tab Tab to expand it into a full code template, with tab-navigable fields for customization.
    • Visual Studio automatically capitalizes keywords (e.g., dim to Dim, as to As, integer to Integer), which is a function of the IDE, not the Visual Basic language itself.
    • Tools on the toolbar like “comment out the selected lines” (Ctrl+K, Ctrl+C) and “uncomment the selected lines” (Ctrl+K, Ctrl+U) aid in code management.

    Important Considerations for Visual Basic Development in Visual Studio

    • While Visual Basic is considered forgiving, precision in typing code is extremely important; even a single character deviation can prevent compilation.
    • Visual Basic is case-insensitive, meaning myfirstname and MyFirstName are treated as the same variable.
    • You cannot declare the same variable name twice within the same code block, regardless of casing.
    • When working with dates, strings, or other data types, Visual Studio, in conjunction with the .NET Framework Class Library, provides numerous built-in methods (e.g., ToString, Parse, Trim, AddDays, AddHours) for common manipulations. It’s advised to utilize these built-in functions rather than writing custom, complex code.
    • Visual Studio simplifies working with namespaces by offering suggestions (e.g., a light bulb icon) to import necessary namespaces (like System.Text for StringBuilder) when a class is not immediately found.

    This course does not aim to be an exhaustive tour of Visual Studio; other resources on Microsoft Virtual Academy offer more in-depth coverage of its advanced features, workflow improvements, and version differences.

    Visual Basic Programming Fundamentals and Concepts

    Programming concepts encompass the fundamental ideas and building blocks used to write software applications. Visual Basic, as a programming language, alongside Visual Studio, an integrated development environment (IDE), provides tools and structures to implement these concepts for building applications primarily on the Windows platform.

    Here’s a discussion of key programming concepts as detailed in the sources:

    Core Building Blocks of Code

    • Statements: These are complete instructions or thoughts in Visual Basic, similar to sentences in English. They are executable instructions given to the compiler.
    • Expressions: Statements are composed of one or more expressions. Examples include a method call (e.g., Console.WriteLine(“Hello World”)), an evaluation in an If statement (e.g., userValue = 1), or an assignment (e.g., x = 7).
    • Operators: These are similar to verbs in a sentence and act on operands. They perform actions. Examples include:
    • Assignment operator (=): Assigns a value to a variable (e.g., x = 7).
    • Arithmetic operators: Addition (+), subtraction (-), multiplication (*), division (/).
    • Equality operator (=): Checks if two values are equal, used in contexts like If statements.
    • Comparison operators: Greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=). These can be used with numbers, dates, or strings.
    • Conditional operators: Logical And and Or to combine expressions.
    • Member access operator (.): Used to call a method or access a property of an object or class (e.g., Console.WriteLine).
    • Literal string operator (“”): Defines a literal string of characters.
    • Concatenation operator (&): Appends or ties together strings.
    • Method invocation operator (()): The parentheses used after a method name to invoke its execution.
    • Type declaration operator (As): Used to define the data type of a variable or property (e.g., Dim x As Integer).
    • Operands: These are similar to nouns and are the “things” that operators act upon. Examples include variables, literal strings, or literal numbers.

    Code Structure and Readability

    • Keywords: Visual Basic uses specific keywords (e.g., Dim, As, Integer, Sub, Module). Visual Studio often auto-capitalizes these keywords for you.
    • Syntax Rules and Precision: Programming languages have specific syntax rules and precision is extremely important when typing code; even a single character deviation can prevent compilation. Visual Studio helps by providing red squiggly lines under problematic code and listing errors in the Error List window.
    • Indentation and White Space: While optional for execution, Visual Studio automatically indents code to denote containment and improve readability. White space also does not affect execution but significantly improves readability.
    • Color Coding: Visual Studio uses color coding for different types of instructions (e.g., literal strings in deep red, classes/modules in aqua, keywords in royal blue, comments in green) to enhance readability.
    • Code Comments: A single quote mark (‘) is used in Visual Basic to comment out a line of code, meaning the compiler will ignore it during execution. This is useful for experimentation without deleting code. Visual Studio also has toolbar buttons and keyboard shortcuts to comment/uncomment selected lines.

    Data Management

    • Variables: A variable is fundamentally a “bucket” in your computer’s memory capable of holding a value. You can store, retrieve, and even overwrite values in a variable.
    • Declaration: You must declare variables using the Dim keyword and specify their data type (e.g., Dim x As Integer). This tells the .NET runtime to allocate appropriate memory space.
    • Initialization: You can set a variable’s value immediately at the point of declaration, which is called initializing. This puts the variable into a “valid state” and can reduce code.
    • Data Types: Visual Basic supports various data types to store different kinds of data:
    • Integer: For whole numbers without decimal places, capable of storing large positive or negative values (e.g., up to ~2 billion).
    • String: For sequences of individual characters (text). Strings can hold a lot of information and are considered “massive buckets”.
    • Boolean: For true/false values, requiring very little memory.
    • Date: For storing dates and times.
    • TimeSpan: For representing spans or durations of time between two dates.
    • Decimal: For precise monetary values or numbers with many decimal places.
    • Case Insensitivity: Visual Basic is case-insensitive, meaning myfirstname and MyFirstName are treated as the same variable. However, you cannot declare the same variable name twice within the same code block, regardless of casing. Visual Studio might automatically capitalize keywords for consistency, but this is an IDE feature, not a language requirement.
    • Type Conversion: It’s often necessary to convert values between data types (e.g., from a string retrieved from user input to an integer for calculations). Methods like CInt (convert to integer), CStr (convert to string), Parse (for dates), and ToString are used for this.
    • String Manipulation: Strings are “immutable,” meaning changing a string creates a new one in memory. For efficiency with large or frequently modified strings, the StringBuilder class is recommended. Common string manipulations include:
    • Escaping Characters: Using double double-quotes (“”) to represent a literal double quote within a string.
    • Special Characters: Using constants like VbNewLine for line breaks or VbTab for tab spacing within strings.
    • Formatting (String.Format): Using replacement syntax (curly braces {0}, {1}, etc.) to insert values into a string template, with options for specific formatting like currency (:C), numbers (:N), or percentages (:P).
    • Methods: Substring (to pull parts of a string), ToUpper (to uppercase), ToLower (to lowercase), Replace (to substitute characters), Length (to get string length), Trim (to remove leading/trailing spaces), TrimStart, TrimEnd.
    • Date and Time Manipulation: The Date data type provides methods for:
    • Getting Current Time: The Now function returns the current date and time.
    • Formatting: ToLongDateString, ToShortDateString, ToLongTimeString, ToShortTimeString for predefined formats. ToString with custom format strings (e.g., MMMM for full month name) for more control.
    • Calculations: AddDays, AddHours, AddMonths, AddYears, etc., to add time, or use a negative number to subtract time.
    • Creating Specific Dates: Using the New Date constructor with year, month, day, and optional time components, or Date.Parse to convert a string into a date.
    • Time Spans: The TimeSpan data type represents a duration of time and can be calculated by subtracting one date from another (Date.Now.Subtract(myBirthDate)). It offers properties like TotalDays, TotalHours, etc..

    Program Flow Control

    • Conditional Logic (Decisions): This allows applications to execute different blocks of code based on conditions.
    • If…Then…ElseIf…Else…End If: Evaluates a condition; if true, a specific block of code executes. ElseIf provides alternative conditions, and Else acts as a catch-all if no preceding condition is true. A single If statement can be condensed onto one line using Then.
    • IIf (Immediate If) Method: A conditional method that evaluates a condition and returns one value if true, another if false, often used for assignments.
    • Iteration (Loops): These statements allow code blocks to be executed multiple times.
    • For…Next: Used to iterate a preset number of times, controlled by a counter variable, a starting value, and an ending value. The Step keyword can be used to count by increments other than one (e.g., Step 2 for odd numbers, Step -1 to count backwards).
    • For Each…Next: Iterates through each item in an array or collection, often more elegant for processing all elements without needing to manage indexes.
    • While…End While: Continuously executes a block of code as long as a specified condition remains true. This is useful when the number of iterations is not known beforehand.
    • Do While…Loop: Similar to While, but guarantees that the code block will execute at least once before the condition is evaluated.
    • Exit For: Used to break out of a For loop prematurely once a certain condition is met.
    • Debugging Tools: Visual Studio offers robust debugging capabilities to understand program flow:
    • Breakpoints: Set by clicking in the gray column next to a line number, they pause code execution at that point.
    • Conditional Breakpoints: Can be configured to stop only when a specific condition is met (e.g., index = 7).
    • Stepping Through Code: Step Over (F10) executes code line by line, allowing inspection of changes.
    • Variable Inspection: Hovering over variables reveals their current values, and windows like Autos, Locals, and Watch display values (which turn red when they change).

    Code Organization and Reusability

    • Methods (Subroutines and Functions): These are named blocks of code that perform a specific task.
    • Benefits: They help to organize code, eliminate duplicate code (reducing the need for copy-pasting), encapsulate specific features (making them reusable), and simplify updates as changes only need to be made in one place.
    • Subroutines (Sub): Execute a block of code and then end quietly, without returning a value (e.g., DisplayResult).
    • Functions (Function): Execute a block of code and return a value of a specified data type (e.g., GetReverseString As String).
    • Input Parameters: Data can be passed into methods using parameters defined in their signature (e.g., (message As String)). Multiple parameters are separated by commas.
    • Overloading: Multiple versions of a method can be created with the same name but different method signatures (the number and data type of input parameters).
    • Passing by Value (ByVal) vs. by Reference (ByRef):
    • ByVal (default): A copy of the argument’s value is passed. Changes inside the method do not affect the original variable.
    • ByRef: A reference to the argument’s memory location is passed. Changes inside the method directly manipulate the original variable.
    • Code Readability: Good method names and breaking down large tasks into smaller methods improve code readability, making it easier for others (or your future self) to understand and maintain. A guideline, often called the “six-line rule,” suggests that no method should have more than six lines of code, promoting smaller, more focused methods.
    • Arrays: An array is a sequence or grouping of related data of the same data type, all collected under a single variable name.
    • Declaration: Declared with Dim and specified size (e.g., Dim numbers(4) As Integer for five elements, as arrays are zero-based) or initialized with values directly (e.g., Dim names() As String = {“Bob”, “Jim”}).
    • Accessing Elements: Individual elements are accessed using their index in parentheses (e.g., numbers(0)).
    • Length Property: Returns the total number of items in the array.
    • Runtime Exceptions: Trying to access an array element outside its defined range (an “index out of range exception”) will cause a runtime error.
    • Classes: A class is a blueprint or custom data type that serves as a container for related properties and methods.
    • Object-Oriented Programming (OOP): Classes introduce object-oriented programming concepts.
    • Object (Instance): An object is a concrete realization or instance of a class created in memory using the New keyword (e.g., Dim myCar As New Car). Just as many houses can be built from one blueprint, many distinct objects can be created from one class. Each object is separate and distinct.
    • Properties: These are attributes of a class or object (e.g., Make, Model, Year, Color for a Car class). They can be simple “auto-implemented” properties or “full-blown” properties with custom Get (retrieve value) and Set (assign value) logic for validation or access control.
    • Methods of a Class: Classes also contain methods (subroutines or functions) that define the behaviors of objects created from that class. For example, a Car class might have a DetermineMarketValue method.
    • Namespaces: Classes are organized into namespaces (e.g., System.Text for StringBuilder), which are like “last names” or “shelves” in a library to help locate them.
    • Inheritance: All classes in .NET, including custom ones, inherit from System.Object, providing some basic functionality for free (like ToString, GetType).

    Understanding these programming concepts provides a solid foundation for developing applications in Visual Basic and beyond.

    Visual Basic: Data Types and Variables

    Data types are a fundamental concept in Visual Basic programming, defining the kind of data a variable can hold and how much memory it requires.

    Here’s a discussion of data types based on the sources:

    • Purpose of Data Types
    • When you declare a variable, you must express your intent regarding the kind of data it will store. This is crucial for the .NET runtime (also known as the Common Language Runtime or CLR) to allocate space in your computer’s memory that is sufficiently large enough to hold the data.
    • By specifying a data type, you tell the runtime the “size of the bucket” you want to create in memory. This ensures that the data is handled correctly and efficiently.
    • Common Built-in Data Types
    • Integer: This data type is used for numeric values that have no fractions or values after a decimal place. It can store numbers ranging from approximately -2.147 billion to +2.147 billion. If you need to store numbers larger than this, you would need a different, larger “bucket”.
    • String: Used to store strings of individual characters. This can be a name like “Bob” or “Tabor”. The string “bucket” is considered “massive” compared to other data types. Strings are also described as “immutable,” meaning changes to a string behind the scenes involve creating new memory allocations.
    • Boolean: A small data type used to store true or false values (represented as 0 or 1).
    • Date: Allows you to work with dates and times. You can initialize a Date variable to a specific point in time (past, present using the Now function, or future) or parse it from a string.
    • Time Span: This is a data type that represents a span or duration of time, such as “three years,” “five years,” or “a thousand days,” rather than a specific date. You can perform calculations like adding or subtracting time spans.
    • Decimal: Used when dealing with monetary values. Unlike integers, it allows for values after the decimal place.
    • Declaring and Initializing Variables with Data Types
    • Variables are declared using the Dim keyword, followed by the variable name, the As keyword, and then the data type. For example: Dim x As Integer or Dim myFirstName As String.
    • Values are assigned to variables using the assignment operator (=). For example: x = 7 or myFirstName = console.readline().
    • You can also initialize a variable’s value at the point of declaration. This sets the variable to a “valid state” immediately. For example: Dim myFirstName As String = “Bob”.
    • Working with Data Types
    • Case Insensitivity: Visual Basic is case insensitive when it comes to variable names, meaning myFirstName and MyFirstName are treated as the same variable. You cannot declare the same variable twice, even with different casing.
    • Data Type Conversion: You often need to convert data from one type to another. Examples include CInt() to convert a string to an integer, or CStr() to convert a number to a string. While Visual Basic can be “forgiving” and sometimes perform automatic conversions, it’s recommended to be deliberate about type conversion using explicit methods to avoid potential problems.
    • Formatting: Data types like strings and dates can be formatted for display using replacement syntax within String.Format or Console.WriteLine. This allows for custom display of numbers (e.g., as currency or with commas) and dates (e.g., month name, short date string).
    • Custom Data Types (Classes)
    • Beyond the built-in data types, you can create your own custom data types using classes.
    • A class acts as a blueprint or a “cookie cutter” for creating objects. It allows you to group related properties (attributes) of different data types together into a single logical container.
    • For instance, a Car class could have properties like Make (String), Model (String), Year (Integer), and Color (String).
    • When you instantiate a class, you create an object, which is a distinct “bucket” in memory based on that class definition. For example, Dim myCar As New Car() creates an object (an instance) of the Car class, allowing you to set and retrieve its properties like myCar.Make = “Toyota”.

    Visual Basic Code Organization and Best Practices

    Code organization is a crucial aspect of developing applications in Visual Basic, providing structure and enhancing the readability and maintainability of your code. It involves arranging your code into logical units, which helps in managing complexity, reducing duplication, and facilitating teamwork.

    Here are the key aspects of code organization discussed:

    • Fundamental Organizational Units: Modules and Classes
    • At a high level, your Visual Basic code is organized within code blocks. These blocks define containers for your code.
    • Modules are simple organizational tools, acting as containers for related methods (subroutines and functions).
    • Classes are also containers for methods, but they have a “special purpose” related to object-oriented programming. They serve as blueprints or “cookie cutters” for creating objects, allowing you to group related properties (attributes) and methods into a single logical container. For example, a Car class can define properties like Make, Model, Year, and Color that are applicable to every car.
    • Methods: The Building Blocks within Containers
    • A method (an umbrella term for subroutines and functions) is simply a block of code that is given a name.
    • Methods help to:
    • Better organize code.
    • Eliminate duplicate code and the need for copying and pasting, which can introduce bugs.
    • Encapsulate specific features, making them reusable across the application.
    • Simplify updates; changes made in one method benefit all places where that method is called.
    • The concept of a method signature (the number and data type of input parameters) allows for overloaded methods, where multiple versions of a method can exist with the same name but different input parameter configurations.
    • A useful guideline for method organization suggests that “no method should have more than six lines of code in it,” promoting tidy and readable code.
    • Classes and Objects: Blueprints and Instances
    • A class defines the blueprint for creating an object. It’s like a cookie cutter that defines the shape.
    • An object is an instance of a class. It’s the “cookie” created from the cookie cutter, a distinct “bucket” in the computer’s memory based on the class definition.
    • You instantiate a class using the New keyword, which brings an object to life in memory. Once instantiated, you can set and retrieve its properties, such as myCar.Make = “Toyota”.
    • Project and Solution Structure
    • Code files (like Module1.vb or Car.vb) are organized into projects.
    • Projects are then compiled into a .NET assembly.
    • One or more projects are organized into a solution, which acts as an overarching “umbrella”. While starting with one project per solution is common, more complex business applications often manage multiple related projects within the same solution for better code management.
    • The Solution Explorer in Visual Studio provides a tree-like view for navigating the files and settings within projects and solutions.
    • By default, projects are saved in your user’s Documents\Visual Studio\[Version]\Projects directory.
    • Principles for Readable and Maintainable Code
    • Human Readability: Strive to make your code “read as much like an English story as possible”.
    • Naming Conventions: Use descriptive names for variables and methods. Camel casing (e.g., myFirstName) is a common convention for local variables.
    • Indentation and Whitespace: While optional for execution, Visual Studio automatically indents code to denote containment and improve visual readability.
    • Color Coding: Visual Studio uses different colors for literal strings, classes, modules, and keywords to enhance code readability.
    • Comments: Use a single quote mark (‘) to add comments or to temporarily “comment out” lines of code, effectively deleting them without removing them from the source.
    • Line Continuation Character: The underscore (_) allows you to split a single logical line of code onto multiple physical lines, improving readability for very long statements.
    • Minimize Duplicate Code: Avoid copy-pasting segments of code; instead, encapsulate reusable logic within methods.
    • Be Deliberate with Types: Although Visual Basic is “forgiving” and might attempt automatic data type conversions, it’s recommended to be explicit about type conversions (e.g., using CInt(), CStr(), or ToString()) to avoid potential issues.
    Visual Basic Tutorial for Beginners – Full Course

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • C# Programming: Syntax, Variables, Iteration, and Core Concepts by Bob Tabor

    C# Programming: Syntax, Variables, Iteration, and Core Concepts by Bob Tabor

    The text is a comprehensive C# programming course designed for beginners. It initiates with Visual Studio installation, progresses to basic “Hello World” applications, and incrementally introduces concepts like variables, data types, operators, and control flow statements. The course then transitions to object-oriented programming, covering classes, objects, methods, properties, and their lifecycle management. Furthermore, it explores the .NET Framework Class Library, assemblies, namespaces, and external libraries, providing guidance on accessing and utilizing them in projects. The course also covers data structures like arrays, lists, and dictionaries, as well as LINQ for data manipulation and querying. Finally, it concludes with an overview of important software development concepts like debugging and design patterns.

    C# Programming Fundamentals Study Guide

    Quiz

    Answer each question in 2-3 sentences.

    1. What is the purpose of the Console.ReadLine() method in C#?
    2. Explain the difference between a variable declaration and variable initialization.
    3. What is the difference between the Console.Write() and Console.WriteLine() methods?
    4. What is an integer data type, and what range of values can it typically hold in C#?
    5. Describe the purpose of an if statement in C# and how it controls the flow of execution.
    6. What is the difference between a single equal sign (=) and a double equal sign (==) in C#?
    7. What is a “for loop” used for in programming and explain the three parts of a for loop.
    8. What is an array in C#?
    9. What is a class in C#?
    10. What is a method in C#?

    Quiz Answer Key

    1. The Console.ReadLine() method is used to read a line of text entered by the user from the console window. It pauses the program’s execution until the user enters text and presses the Enter key, then returns the entered text as a string.
    2. Variable declaration is the process of naming a variable and defining its data type, while variable initialization is the process of assigning an initial value to a previously declared variable.
    3. Both methods output text to the console, but Console.Write() leaves the cursor at the end of the output, while Console.WriteLine() moves the cursor to the beginning of the next line after the output.
    4. An integer is a whole number (without any decimal or fractional part). In C#, the int data type can typically hold values between approximately -2.147 billion and +2.147 billion.
    5. An if statement is a conditional statement that executes a block of code only if a specified condition is true. If the condition evaluates to false, the code block is skipped.
    6. A single equal sign (=) is an assignment operator used to assign a value to a variable. A double equal sign (==) is a comparison operator used to check if two values are equal, returning a Boolean value (true or false).
    7. A for loop iterates through a code block for a specified number of times. 1: Initialization(where you declare and initialize variables), 2: Condition(the condition for the loop to continue running), and 3: Increment(where you increment or decrement the loop variables).
    8. An array in C# is a data structure that stores a fixed-size, sequential collection of elements of the same data type. Each element in the array can be accessed by its index.
    9. A class is a blueprint for creating objects that define data (fields) and actions (methods). Classes define the properties and behaviors of the objects that will be created from them.
    10. A method is a block of code that performs a specific task and can be called by name from other parts of the program. Methods can accept input parameters and return a value.

    Essay Questions

    1. Explain the importance of understanding data types in C# and how choosing the correct data type can impact the performance and accuracy of a program. Provide examples of common data types and scenarios where each would be most appropriate.
    2. Discuss the role of decision statements (if, else if, else) in programming logic. Provide a detailed example of a scenario where multiple decision statements are used to handle different conditions, and explain how these statements control the flow of execution.
    3. Describe the concept of variable scope in C# and explain how it affects the accessibility and lifetime of variables. Provide examples of local, class-level, and global variables, and discuss the implications of each scope.
    4. Explain the purpose and benefits of using loops (for, while, do-while) in programming. Provide a detailed example of a scenario where a loop is used to iterate through a data structure, perform calculations, and output results, and discuss the different types of loops that could be used in that scenario.
    5. Discuss the key principles of Object-Oriented Programming (OOP) such as encapsulation. Explain how using classes and objects can improve code organization and maintainability.

    Glossary of Key Terms

    • Class: A blueprint or template for creating objects, defining their properties (fields) and behaviors (methods).
    • Console: A system output window where a program can display text and receive input from the user.
    • Data Type: Specifies the type of data a variable can hold (e.g., integer, string, boolean).
    • Declaration: The process of naming a variable and defining its data type.
    • Expression: A combination of operands and operators that evaluates to a single value.
    • Field: A variable that is a member of a class or struct.
    • For Loop: A control flow statement for specifying iteration, which allows code to be executed repeatedly.
    • If Statement: A conditional statement that executes a block of code if a specified condition is true.
    • Initialization: Assigning an initial value to a variable when it is declared.
    • Integer: A whole number without any fractional or decimal parts.
    • IntelliSense: A code completion feature in Visual Studio that suggests code elements as you type.
    • LINQ: Language Integrated Query, is a feature in C# that provides a unified way to query data from various sources.
    • Method: A block of code that performs a specific task and can be called by name.
    • Object: An instance of a class, created from a blueprint or template.
    • Operand: A value or variable on which an operator acts.
    • Operator: A symbol that performs an operation on one or more operands.
    • Property: A member of a class that provides a flexible mechanism to read, write, or compute the value of a private field.
    • Scope: The region of a program where a variable is accessible.
    • Semicolon: A character (;) used at the end of a C# statement to indicate the end of the statement.
    • Statement: A complete instruction in C#, often ending with a semicolon.
    • String: A sequence of characters.
    • Variable: A named storage location in memory that can hold a value of a specific data type.

    C# Programming Fundamentals with Visual Studio: A Beginner’s Guide

    Here’s a detailed briefing document summarizing the key themes and ideas from the provided source excerpts.

    Briefing Document: C# Programming Fundamentals with Visual Studio

    Overview:

    This document summarizes a series of instructional excerpts focused on teaching fundamental C# programming concepts using Visual Studio. The excerpts cover a range of topics, from setting up Visual Studio and creating basic “Hello World” applications, to declaring variables, using decision statements (if/else), understanding operators, working with iteration (for loops), arrays, LINQ, enums and switch statements, methods and debugging techniques. The material is designed for beginners with little to no prior programming experience. The instructor, Bob Tabor, emphasizes hands-on learning and provides practical examples.

    Key Themes and Ideas:

    1. Basic Workflow and Environment Setup:
    • Custom Installation of Visual Studio: The course begins by guiding users through a custom installation of Visual Studio. The narrator explains the selection and installation process, including the option to review license terms for each software component.
    • Creating a New Project: The initial lessons focus on establishing a basic workflow in Visual Studio. This includes creating new projects using templates (e.g., Console Application). “To begin, we’re going to create a new project. There are a number of different ways to do this, but I’m going to keep it simple and go to ”File” ”New” ”Project””.
    • “Hello World” Application: The course begins with building a “Hello World” application. The purpose is to familiarize the student with the basic steps of coding such as creating a new project, writing code, testing the application, saving the project, and debugging any errors.
    1. Variables and Data Types:
    • Variables as Buckets: Variables are explained as “buckets” in computer memory that hold data. “A variable is simply under the hood, a bucket. I guess you could call it in the computer’s memory and you put things in buckets and you dump things out of buckets”.
    • Declaring Variables: The importance of declaring variables and specifying the correct data type is emphasized. “We have to declare our variables, we have to create those buckets and then give them some label that we can refer to them with from that point on.”
    • Data Types Covered: int (integers), string (text), and others. The course highlights the importance of choosing the right data type for the data being stored.
    • Variable Initialization: The course explains how to initialize the value to variables upon declaration. “What I’m doing here is not only declaring the variable, but then I’m initializing its value to whatever we retrieve when we call Read Line. This is called initialization, and initialization is important because you want to give your variables a value as quickly as possible”.
    1. Decision Statements (if/else):
    • Conditional Logic: The course covers the use of if statements to execute code blocks based on conditions. “The if statement is called the decision statement because we will decide whether to execute any of the code inside of this inner code block based on this evaluation that we’re going to do after the if keyword”.
    • Comparison Operators: The use of double equal signs (==) for evaluation of “true or false” is covered and how to differentiate this from assignment operator using only one equal sign.
    • else if and else: The course includes the use of else if for additional conditions and else for “catch-all” scenarios.
    • Nested Decisions: The course also discusses how to nest ‘if’ statements within each other.
    1. Operators, Expressions, and Statements:
    • Building Blocks of Code: The course defines statements as complete thoughts, expressions as parts of statements, and operators and operands as components of expressions. “Statements are what you call complete thoughts in C#. Typically, one line of code. A statement is made up of one or more expressions and expressions are made up of one or more operators and operands”.
    • Types of Operators: Mathematical operators (+, -, *, /), assignment operators (=), equality operators (==), comparison operators (>, <, >=, <=), logical operators (&&, ||), and the inline conditional operator (?:) are described.
    1. Iteration (for Loops):
    • Looping Constructs: The course introduces for loops for iterating through code blocks a specified number of times.
    • Increment Operator: The i++ increment operator is explained.
    • break Statement: The break statement is introduced as a way to exit a loop prematurely.
    • Code Snippets: Code snippets are a pre-built piece of code to help users construct more complex code without needing to remember syntax perfectly. “To do this it’s real easy. If you can remember I need a for iteration statement just type in the word for. You’ll see that it pops up in the IntelliSense”.
    1. Debugging Techniques:
    • Breakpoints: The use of breakpoints to pause code execution and examine variables is explained. “To make this work, what I’m going to do is actually set a breakpoint here on this line of code.”
    • Stepping Through Code: The process of stepping through code line by line to understand the flow of execution is also covered.
    • Variable Monitoring: The ability to monitor variable values during debugging is highlighted.
    1. Arrays:
    • Storing Collections of Data: The course addresses how to create arrays to store multiple related values.
    • Array Declaration and Initialization: The method of declaring the array and initializing the array elements are both discussed.
    • Array Operations: The discussion covers how to retrieve values from an array using indexing, as well as how to utilize a for loop to print out the values in an array.
    1. LINQ (Language Integrated Query):
    • Querying Collections: The course discusses using LINQ to query and manipulate collections of data (like arrays or lists).
    • Extension Methods: Discusses method syntax and query syntax available in LINQ.
    • var Keyword: The use of the var keyword to allow the compiler to infer the data type of a variable is explained, especially in the context of LINQ queries. “The var keyword is essential to help us to be able to create these very complex queries, and not have to worry about what the data type of it is that’s returned.”
    • Anonymous types: The course discusses anonymous types and how those get used as part of a LINQ query.
    1. Enums and Switch Statements
    • Enumerations: Enumerations are a data type that limits and constrains all possible values to only those that are valid and have meaning within the system.
    • Switch Statement:. The course includes the introduction of a switch statement as an easier decision statement to read for situations with many different potential cases.
    1. Methods:
    • Defining Reusable Code Blocks: Methods are introduced as reusable blocks of code. “What we’re going to do now is create and talk about methods. Methods are essentially a way to take a series of code statements, give them a name, and then re-execute them over and over again throughout our applications.”
    • Method Parameters and Return Types: The course explains the use of input parameters and return types for methods.
    • Overloading Methods: Overloading is the method of creating two methods with the same name but different methods signatures is discussed.
    1. Understanding Scope
    • Scope of Variables: This section explains how the location where a variable is declared impacts its accessibility within the code. “Whenever you declare variable inside of a block of code, that variable is only alive for the life of that code block and any of the interior code blocks or code blocks inside of that code block.”
    • Accessibility Modifiers: The difference between public and private is touched upon.
    1. Assemblies and Namespaces
    • .NET Assemblies: A discussion about how the .NET framework splits the code into multiple files. “These code files are called.NET assemblies. In fact, even the applications that we build, they’re ultimately compiling into.NET assemblies.”
    • .Namespaces: Used to be able to tell one class from a different class. “The creators needed a way to be able to tell one class from a different class and so they introduced the notion of name spaces and name spaces are like last names for your classes”.
    1. Working with Strings
    • .Formatting Strings: How to use formatting codes to represent strings (e.g. as a percentage) are discussed.
    • .Manipulating Strings: Several functions are described such as Substring, ToUpper, Replace, and Trim.
    1. Creating Classes
    • .Properties: A class contains the data and functionality related to one “thing” in your code and a property is the actual data point.
    • .Objects: After defining the class, you can create instances of that class.
    1. Events
    • .Events Handlers: Used for the situations when you want more than one event handler to execute whenever the event is raised

    Instructor’s Style:

    • Beginner-Friendly: The instructor aims to simplify complex topics and use analogies to make them more understandable.
    • Emphasis on Practice: The course encourages viewers to type code along with the instructor to reinforce learning.
    • Problem-Solving Focus: The instructor emphasizes the importance of developing problem-solving skills by identifying differences in code and debugging errors.
    • IntelliSense Reliance: The course also highlights how software developers rely on IntelliSense (Visual Studio’s code completion feature) to help them write code quicker.

    Target Audience:

    The material is designed for individuals who are new to programming and want to learn C# using Visual Studio. No prior programming experience is assumed.

    Conclusion:

    These excerpts provide a structured introduction to C# programming, covering essential concepts and practical skills for beginners. The instructor’s clear explanations and hands-on approach make the material accessible and engaging for novice programmers.

    Visual Studio and C# Development: FAQ

    Visual Studio and C# FAQ

    • How do I perform a custom installation of Visual Studio 2015?
    • After clicking the “Next” button in the installer, you will see a screen displaying all the different items you have selected. By clicking “Install”, you agree to the license terms for all selected software components. You can click on each item to view its specific license terms. Once you are satisfied, clicking the “Install” button begins the installation of all chosen components.
    • What is the basic workflow for creating a simple C# application (like “Hello World”) in Visual Studio?
    • The basic workflow involves creating a new project by going to File -> New -> Project and selecting “Templates” then “C#”. Choose “Console Application,” rename the project (e.g., “HelloWorld” using CamelCase). Type your C# code within the innermost set of curly braces in the program.cs file. Test your application by running it, and save your project frequently.
    • What are variables in C# and how do I declare them?
    • Variables are like “buckets” in the computer’s memory that hold data. To declare a variable, you must specify its data type (e.g., int for integers, string for text) and give it a name (e.g., int x;, string myName;). This tells the compiler to allocate the appropriate amount of memory for that type of data.
    • What is the difference between the assignment operator (=) and the equality operator (==) in C#?
    • The single equal sign (=) is the assignment operator. It assigns the value on the right-hand side to the variable on the left-hand side (e.g., x = 7;). The double equal sign (==) is the equality operator. It compares the values on both sides and returns a boolean value (true if they are equal, false otherwise) (e.g. if (userValue == “1”)).
    • What is an “if” statement and how does it work?
    • An if statement is a decision statement that allows you to execute a block of code only if a certain condition is true. It can be followed by else if statements to check additional conditions, and an else statement to execute a block of code if none of the conditions are true.
    • What are operators and operands in C#?
    • Operators are symbols that perform actions on operands. Operands are the data that operators act upon. For example, in x = 7 + 3;, + is the addition operator, = is the assignment operator, and x, 7, and 3 are operands. Operators can perform arithmetic, comparisons, logical operations, and more.
    • What is a “for” loop and how do I use it?
    • A for loop is an iteration statement that allows you to repeatedly execute a block of code a specific number of times. Its syntax typically includes an initialization (declaring a variable), a condition (determining when to stop looping), and an increment/decrement (modifying the variable after each iteration). (e.g. for (int i = 0; i < 10; i++) { Console.WriteLine(i); })
    • What are classes and objects in C# and why are they important?
    • A class is a blueprint for creating objects. It defines the properties (data) and methods (actions) that an object of that class will have. An object is an instance of a class. Classes and objects are fundamental to object-oriented programming, allowing you to organize code into reusable and manageable units. They help in modelling real-world entities and their interactions within your program.

    Customizing Your Visual Studio Installation

    A custom installation of Visual Studio allows you to select the specific features, languages, and tools that you want to install, rather than installing everything by default. The source recommends selecting the “Custom Option” during installation to ensure you obtain the necessary packages and libraries for your desired applications.

    Key aspects of a custom Visual Studio installation:

    • Programming Languages You can choose to install additional programming languages such as Visual C++, Visual F#, and Python Tools for Visual Studio. By default, only C# and Visual Basic templates are installed.
    • Windows and Web Development Options include ClickOnce Publishing Tools, SQL Server Data Tools, PowerShell Tools for Visual Studio, and Silverlight Development.
    • Universal Windows App Development To develop universal windows applications, you must ensure that you have the tools, emulators, and SDK. While you can install the Windows 10 SDK later, it is easier to install these during the initial Visual Studio installation.
    • Cross-Platform Mobile Development If you want to develop applications for Windows Phone, iOS, and Android using C#, you can select the cross-platform mobile development tools for the Xamarin platform. This option includes all the emulators as well.
    • Additional Tools You can install Git for Windows and the GitHub extension for Visual Studio to integrate with GitHub source control projects.

    Keep in mind that selecting additional options will increase the installation size of Visual Studio. Before installing, you can review each item to ensure you have all the components, tools, and SDKs necessary for your development platforms of choice.

    C# Hello World Application: A Beginner’s Guide

    The “Hello World” application is a simple program designed to demonstrate the basic workflow of writing code in C#. It involves printing the words “Hello World” to a console window. The purpose of this exercise is to familiarize you with the steps involved in creating a new project, writing code, testing the application, handling errors, and saving the project.

    Key aspects of creating a “Hello World” application in C#:

    • Creating a New Project To begin, navigate to “File,” then “New,” and then “Project” in Visual Studio to open the new project dialog. Select “Templates,” then “C#,” and choose the “Console Application” option. Rename the project to “HelloWorld” (using the naming convention of capitalizing the first letter of each word without spaces) and click “Okay”.
    • Writing the Code Locate the innermost set of curly braces {} within the program.cs file. Inside these braces (approximately lines 13 and 14), type the following code:
    • Console.WriteLine(“Hello World”);
    • Console.ReadLine();
    • Console.WriteLine is code from the .NET Framework class library that displays text in the console window. Console.ReadLine() tells the application to wait for user input before continuing execution. Commenting out the Console.ReadLine() will cause the application to execute the WriteLine command and then exit immediately.
    • Running the Application After writing the code, run the application to ensure it prints “Hello World” to the console window. If there are any errors, Visual Studio will typically indicate them with red squiggly lines, providing clues to identify and fix the issues.
    • Precision in Syntax Writing C# code requires precision. Visual Studio provides assistance by highlighting potential issues and offering suggestions. If you encounter problems, compare your code character by character with a known correct version to identify any discrepancies.
    • Understanding the Code The code needs to be written in the correct place, specifically within the opening and closing curly braces of the innermost set as defined by the boilerplate code. These curly braces define code blocks, which have names and purposes. The first code block is named “Main”, also known as a method. The main method lives inside another set of curly braces with the name “program”, which is a class. A class is a container for all the methods of the application. There is another set of curly braces with the name “HelloWorld”, which is a namespace. A namespace is another way of organizing code.

    By following these steps, you can create a simple “Hello World” application and familiarize yourself with the basic C# development workflow.

    Visual Studio: Creating C# Console Applications

    When creating a new project in Visual Studio, there are several key steps and considerations. The following points provide an overview of the process:

    • Initiating a New Project Start by navigating to File > New > Project in Visual Studio to open the new project dialog.
    • Selecting a Template In the new project dialog, select Templates > C#, and then choose the Console Application option. The number of items displayed may vary based on the Visual Studio version and edition.
    • Naming the Project Rename the project to a desired name, such as “HelloWorld”. A common naming convention is to capitalize the first letter of each word without spaces (e.g., HelloWorld).
    • Understanding the Project Structure Visual Studio creates a starting point for a Console Window Application, including a file named program.cs with boilerplate code. The code is written inside the innermost set of curly braces {} within the program.cs file. These curly braces define code blocks, such as methods, classes and namespaces.
    • Project Files and Location By default, Visual Studio stores projects in your Documents folder, under a folder corresponding to your Visual Studio version (e.g., Visual Studio 2015), and then in a Projects folder. This location can be customized.
    • Projects and SolutionsFiles and settings are organized into projects. A project is compiled into a single .Net assembly.
    • One or more projects are organized into solutions. Solutions can contain multiple related projects.
    • Opening Existing Projects Existing projects can be opened from any location on your computer via File > Open > Project/Solution.
    • Project Files on Disk The projects and solutions are stored as files on your hard drive:
    • The .sln file (solution file) contains information about all projects under the solution.
    • The .csproj file (C# project file) contains references to project files, settings, and metadata.
    • The bin folder stores the binary (compiled) version of the application.
    • References Creating a new project using a project template automatically creates references to files in the .NET Framework Class Library. These references can be viewed under the references node of the project in the Solution Explorer.

    Troubleshooting and Resolving C# Errors in Visual Studio

    When learning C#, it’s common to encounter errors, and understanding how to identify and fix them is crucial. Visual Studio provides several tools and visual cues to help in this process.

    Common types of C# errors and how to address them:

    • Build Errors: These occur when Visual Studio is unable to compile your code. A dialog box may appear, stating, “There were build errors. Would you like to continue and run the last successful build?” Always select “no” to review the errors.
    • Error List: After a build error, a list of errors is displayed in the error list. Double-clicking on an error will typically put the mouse cursor on the line where the problem exists.
    • Red Squiggly Lines: Visual Studio uses red squiggly lines to highlight areas of code that likely contain errors. These lines serve as visual cues, indicating where you should focus your attention to identify and correct issues. Blue squiggly lines are similar, also indicating areas that may need attention.
    • Incorrect Code Block: C# commands must be placed within the correct code blocks, typically defined by curly braces {}. An error may occur if code is not placed between the innermost opening and closing curly braces.
    • Missing Semicolon: Just like a sentence needs a period, each C# statement needs a semicolon ; to mark the end of a complete instruction. The error message “Semicolon expected” indicates that a semicolon is missing at the end of a line of code.
    • Syntax Errors: These occur when the code doesn’t follow the rules of the C# language. The error message might say, “Syntax error, something expected”.
    • Case Sensitivity: C# is case-sensitive, meaning that Console is different from console. Ensure that you match the capitalization exactly.
    • Incorrect Spelling: Ensure that all words are spelled correctly, such as WriteLine instead of Writeline.
    • “The name ‘X’ does not exist in the current context”: This error indicates that a variable or name has not been declared or is not accessible in the current scope. This can happen if a variable is used before it is declared or if it is declared within a scope that is not accessible from the current location.
    • Undeclared Variables: If you comment out the declaration of a variable (e.g., int x;), the compiler will not recognize subsequent uses of that variable. Ensure that all variables are properly declared before use.
    • Missing References: If you are utilizing a class that is not recognized, it may be because you are missing a reference to the assembly in your project, or you are missing a “using statement”. Use “Control period” to have Visual Studio suggest the appropriate “using statement”.
    • Compare With Correct Code: If you are struggling to identify the issue, compare your code, character by character, with a known correct version. The source code from the lessons can be downloaded and opened in a separate copy of Visual Studio to compare.
    • Utilize Visual Studio: Take advantage of the tools in Visual Studio to help identify and resolve errors.
    • Scope: Variables declared inside a code block (defined by curly braces) are only accessible within that scope. If you need to use a variable outside of the code block, it must be declared outside of it.
    • Defensive Coding: Code defensively to anticipate and handle potential issues, especially those related to user input, file access, and network connections. Use try-catch blocks to manage exceptions and prevent application crashes.

    By paying close attention to error messages, utilizing the tools available in Visual Studio, and understanding the syntax rules of C#, you can effectively troubleshoot and resolve errors in your code.

    C# String Manipulation Techniques and Best Practices

    String manipulation involves modifying and formatting strings in C#. There are various techniques available for inserting special characters, formatting numbers and dates, changing aspects of strings, and searching or replacing items within strings.

    Key techniques for string manipulation in C#:

    • Inserting Special Characters The backslash character \ is used to escape or insert special characters into literal strings. For example, to include double quotes within a string, use \” before each double quote. To insert a new line, use \n.
    • To use a backslash character itself, either use another backslash character to escape it \\, or add the @ symbol in front of the literal string. This tells C# to use backslash characters as true backslash characters and not as escape sequences.
    • String Formatting with string.Format This method is used to insert values into a string template using replacement codes. The number inside the replacement code {} corresponds to the argument passed into the string.Format method.
    • Replacement codes can be reused multiple times or used in a different order.
    • Special formatting can be applied within the replacement code. For example, {0:C} formats the value as currency, and {0:N} adds commas and decimal points for large numbers. Using {0:P} will display a value as a percentage.
    • Custom formats can be created using pound symbols # to represent each digit.
    • String Manipulation Methods Strings have built-in helper methods for manipulation.
    • Substring(): Extracts a portion of the string, starting at a specified position. You can specify the starting position and the number of characters to extract.
    • ToUpper(): Converts the entire string to uppercase.
    • Replace(): Replaces all occurrences of a specified character with another character. For example, spaces can be replaced with double dashes.
    • Remove(): Removes a specified number of characters from the string.
    • Trim(): Removes leading and trailing spaces from a string. There are also methods to trim only the beginning or ending spaces.
    • String Length The Length property can be used to determine the number of characters in a string.
    • Efficient String Building with StringBuilder When performing a lot of string concatenation or manipulation, using the StringBuilder class is more efficient than repeatedly concatenating strings directly. Strings are immutable, so each concatenation creates a new string object in memory. StringBuilder avoids this by providing an Append method to modify the string in place.

    By using these techniques, you can effectively manipulate strings in C# for formatting, data processing, and display purposes.

    C# Fundamentals for Beginners

    The Original Text

    >> I am Bob Tabor with Developer University, and I welcome you to this course covering the fundamentals of the C-sharp Programming Language and Programming topics in general. Designed specifically for absolute beginners to programming. Now, if you’re already an experienced Software Developer coming from another Software development platform programming language, then frankly, this series of lessons will move much too slowly for you. You might be better served to find another resource to use as a starting point. One with you the experienced beginner to C-sharp in mind and Microsoft Virtual Academy has many great courses designed for people and all skill levels, so I recommend that you start your search there. However, if you are completely new to programming and you’re new to the C-sharp programming language and you’re new to building applications on the Windows platform, then this perhaps is the best place for you to start. Not only will you and I work together to learn the syntax of C-sharp, but I’m going to take the time to walk through everything that we do together. I’ll explain what we’re doing, but more importantly, I want to explain why we’re doing it, the thought process behind it. I’m going to try to anticipate the questions you might have anticipate the problems that you might run into as you’re typing your very first lines of code into the code window or as you’re working through some of the exercises that we’ll work through together. I’ve literally taught hundreds of thousands people, maybe even millions of people C-sharp over the past 14 years. That’s no exaggeration. This includes children as old as eight years old and as young as eight years old from virtually every corner of the world. They’ve all learned from a version of this course, and I know you can learn too. In fact, this is the sixth generation of this very course, dating all the way back to 2005. And over the years, I’ve incorporated feedback from thousands of students feedback and suggestions on how to improve the course. I’ve incorporated those in an effort to make sure that this is the very best effort that I can put forward to help you get your feet well with C-sharp. Now I’ll only make one real assumption as we begin this course, and that’s that you already have some version in addition to Visual Studio already installed on your local computer and you’re ready to write your very first lines of code. Now, if you don’t already have Visual Studio installed, then please by all means, visit Visual Studio.com, where you’ll learn about the many free and commercial editions of Visual Studio that are available. What the differences are. Now, personally, I used Visual Studio 2015 Community Edition, one of the free versions of Visual Studio that are available on Visual Studio.com, and I want to emphasize that you can use any additions and version of Visual Studio with these lessons. Now, there might be tiny User Interface differences between what you see on my screen and what you see on your screen as you work through the videos. However, I’m not going to be focusing on any specific features of Visual Studio, so hopefully that won’t prevent you from following along, no matter what. There will be other courses on Microsoft Virtual Academy that will demonstrate the power of Visual Studio, all the features that Visual Studio has to offer and explain the differences between editions and versions of Visual Studio. But I won’t be focusing on that in this course. I’m going to focus specifically on the basics of the C-sharp Programming Language itself. And what I will demonstrate will be true no matter which version or edition of Visual Studio that you choose to use, and that’s great news, because as long as C-sharp exists, these lessons should still be valid and useful to you, no matter what. So to get the most out of this course or any course that you find online, you really should become an active learner and that takes several different forms. First of all, you should attempt to follow along closely and do what I call getting your hands dirty in the code. Actually writing the code that I’m writing on screen, you’re writing it along with me. All right, there’s no better way to learn how to code than actually write code yourself. It’s like suggesting that somebody learn how to play the guitar without ever touching a guitar. You’d think, Well, that’s virtually impossible. Typing in the code yourself will give you insights that merely watching videos won’t, so pause the video, rewind the video, re-watch portions of the videos as you need to. I’m going to make the code available for download, and you’re welcome to it, and you can use that to compare the code that you write versus the code that I’ve written in the videos. But you really should be typing in everything on your own, in your own local copy of Visual Studio running on your desktop. Also, don’t rush through this course. If something doesn’t make sense again, pause the video. Rewind the video. Re-watch those portions that don’t make complete sense at first. Sometimes a second or third viewing, focusing more specifically on what’s going on around the screen and on the words that I’m saying can help. Being an active learner also means that you’re taking control of the process of learning so if I say something or do something that doesn’t completely make sense, by all means find a second or a third resource that can help you. Maybe it’s an article out on msdn.Microsoft.com or other videos on Channel nine or Microsoft Virtual Academy, but make sure you search out those resources that resonate well for you. If you’re interested in even more comprehensive version of a C-sharp training course that covers a lot more ground in more depth, complete with dozens of coding challenges and over 30 hours of video instruction, then please visit my own website. Devu.com Developer University You’ll also find many other training courses that I’ve created, designed specifically to help you become a professional C- sharp developer someday. Furthermore, over time, as we go through this course and as I begin to fill questions about it, I might add some study resources and additional free content related to the topics in the course that you’re currently watching right now. That’s another reason to be sure to visit me at devu.com, now like I said earlier, if you’re new to programming, I’m really excited for you. Learning to write applications is really one of my life’s passions. It’s extremely gratifying to breathe life into your imagination and watch your creations come to life and watch other people actually then use your applications. You’re embarking on a really exciting journey that’s immersive. It’s personally and professionally rewarding and best of all, I know you can do this again. I’ve seen so many people start off where you’re at right now, and they might even be working professionally, writing code for a living or building real applications that are being sold in App Stores like the Windows Store. If you’ve ever gotten stuck in the past when trying to learn how to program, I promise you that if you put in the time and you put in the effort and you work along with me as we work together, we’re going to build the knowledge of C-sharp that you need to be well equipped to move on to more advanced tutorials where you can learn how to build your own Web Applications, Windows Applications, Windows Store Applications, Cloud Services, Video Games and even applications that will run on iOS and Android using C-sharp. Now, assuming again that you have some version in addition to a Visual Studio already installed and you’re ready to go, then we’re going to begin writing C-sharp in the very next lesson. I hope you’re excited because I really am. This is so much fun. Let’s go ahead and get started. We’ll see you there. Thank you. >> Let’s take a look at how to install Visual Studio using the custom option for this example, we’ll use the Community Edition of Visual Studio 2015 in order to get it. Simply visit visualstudio.com and click on the ”Download Community 2015″ button. Once we’ve clicked on the download, it’ll download to our computer, and it’s a Web installer, so we click on the “Run” button and it will initiate the installation routine for Visual Studio Community 2015. Once we have the option screen available, it’s time to start looking at customizing the Installation of Visual Studio. For the most part, the default allows you to create web and desktop type applications. But if you want to create different styles of applications or include more languages then the ”Custom Option” is what you should be choosing. I always recommend selecting the ”Custom Option” for the Installation of Visual Studio 2017, to ensure that you’re getting the packages and libraries that you need to create the applications you may wish to use. By selecting ”Custom” and clicking on the ”Next” button, we are now brought to the screen and we can select the different features. The first option is programming languages, and if we click the ”Arrow” to expand it, we can see that we have Visual C++, Visual Fsharp and the Python Tools for Visual Studio that are additional programming languages that will get Installed if you select this option. Remember, by default, Visual Studio Community Edition will only Install C-sharp in Visual Basic Templates. Also notice under Visual C++, we have options for the common tools, the Microsoft Foundation Classes and then windows XP support for C++. For my purposes, I’d like to have all of my programming languages available to me, because I create projects using the different languages all the time. I’m going to select ”Checkbox” next to programming languages to install all of those programming types. Also, under windows and web development, we can choose various options here for things such as the ClickOnce Publishing Tools, SQL Server Data Tools, PowerShell Tools or Visual Studio, Silverlight Development, etc. Here’s a very important component, if you want to develop universal windows applications, we need to ensure that we have the tools, the emulators and the SDK. Now you can choose the “Default” Install a Visual Studio, and then come back and Install the Windows 10 SDK at a later time, and that will include the tools, the SDK and the Emulators for you. But it’s so much easier to install these during the Installation of Visual Studio. Please note that it will increase the Install size of the application, so the toolset will be much larger. Again, depending on what it is that you want to do, you may want to select ”Universal Windows App Development Tool Kit” PowerShell Tool for Visual Studio, rather if you want to be using PowerShell tools within your applications. If you need backward compatibility for Windows 8.1, and Windows Phone 8.0 And 8.1, you can select this option. Also, there are some common tools or Cross Platform Mobile Development Tools. These are important if you want to develop applications using the Xamarin platform. Xamarin is a cross platform tool that allows you to create applications for windows phone, for iOS devices and for android devices by using the C-sharp language in Visual Studio. All of these tools are available for the cross platform mobile development using Xamarin platform. It includes all of the emulators as well. Again remember, it will increase the size of the Install base for Visual Studio. You might also notice that because I selected the cross platform mobile development tools, we now have a little box inside the Windows 8.1 and Windows phone tools. If we expand that, we’ll see that it has included tools and Windows SDK, and the reason it does that, is because there’s a potential that you may want to target Windows phone 8.0 or 8.1 applications. The tools and SDKs will also get Installed. At the same time, the common tools checkbox includes a little square box, indicating that we have also added another component here, and that is the Git for windows. We can install Git, which is your source control, GitHub extension for Visual Studio, so that you can integrate with GitHub source control projects, and then an extensibility tools update three for Visual Studio as well. You’ll notice that by selecting all of these options, set up can require up to 48 gigabytes across all of the drives that you will Install it on. Again, review each of the items that you have selected to ensure you have all the necessary components tools SDK for your development tools of choice or platforms of choice, and then select the ”Next” button. Once you do, you basically see equipment or selected features screen that will tell you, all of the different items that you have selected, and by clicking ”Install” you agree to the license terms of all the software components. If you’re not sure what those are, each one of the items that has license terms allows you to click on it to view those. Once you’re satisfied with it, click the ”Install” button in Visual Studio starts installing all of the components that you have selected. This is a quick overview, of how to perform a custom installation of Visual Studio 2015. >> Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. In this lesson, I want to build a super simple C-sharp Application. I want you to follow along. It’s a Hello World Application, meaning that we’re merely going to print out the words Hello World to a Console Window, and the point of this exercise is just to show you the basic workflow. I’m not going to attempt to even explain why we’re doing what we’re doing. The focus will be on, what I’m going to do next and how I’m doing it? In other words, I want you to focus on the basic workflow that’ll be the same for all the applications we will build in this course, and pretty much every Application you’ll ever build using C-sharp. Things like how to create a new project. Where do you type in your C-sharp code? How do you test your application to make sure that it’s running correctly, and what do you do whenever you have an error in your code? How do you save your project? Things of that nature. For now, just try to follow along. Don’t worry if something doesn’t make a lot of sense at this point, that’s really what the rest of this course is for. In the next few lessons. After this one, we’re going to dissect this tiny little application that we built, and I’m going to explain at that point why we did what we did and then what does the code mean and why it’s doing what it’s doing. Just a quick reminder, like I said in the previous video, the introduction of this course, I’m going to assume that you have some version and some additional Visual Studio already Installed, even if your Visual Studio looks a little bit different than mine does on camera here. Don’t be overly concerned about that. The basics are the same, no matter what, I promise. Let’s go and get started here. To begin, we’re going to create a new project. There are a number of different ways to do this, but I’m going to keep it simple and go to ”File” ”New” ”Project” and selecting that menu option will open up the new project dialog. Now, chances are, the number of items that you see here in the center part will be dramatically different than the items that I see based on which version, in addition, a Visual Studio that you have installed. However, you should be able to select ”Templates” and then select ”C-sharp”, and one of the options should be a Console Application. I want you to select that, and then we’re going to rename this project to HelloWorld. Now notice I use a little naming convention, where I use a capital H in Hello, and a capital W in world, and I don’t use a space in between the two words. Now that’s just the naming convention that I came up with to help me identify projects a little bit easier. Something I recommend that you follow. Shouldn’t have to make any other changes in this dialog. I’m going to go ahead and click the ”Okay” button, and Visual Studio will go off and now create the starting point of a Console Window Application for us, and so now you should see in this main area, in this text area, a file opened called program dot.cs and there’s some code here that is already generated for us boilerplate code. We’re going to ignore most of that, except we’re going to find this innermost set of Curly Braces. One of the first things you’re going to need to do when you’re learning how to develop Software is tell the difference between a parentheses, curly braces, square brackets, angle brackets and I don’t know that I left out any. But here we want the curly braces look like little mustaches turned on their side. These are important, and I want to go inside of those two that opening and closing curly brace and make some room for ourselves. This is where we’re going to type our code. It’s approximately Line 13 and 14, at least in my copy of Visual Studio. Then I’m going to type in the following, type in Console and you may notice now this little window pops up below what I’m typing. You can safely ignore that for now. Eventually, this becomes our best friend. But for now, it might be distracting and give it away to try to ignore it and type in everything by hand to the best of your ability. Console, and then I want to use the period on the keyboard, I’m going to call it the dot. Console dot, and then capital W Write capital L Line. Next, I’m going to use an opening and closing parentheses, so that’s not a curly brace. These are just the characters you’d use for a smiley face, and an emoticon. Then inside of there and use the arrow keys on my keyboard navigate around here. I’m going to go inside of the opening and closing parentheses, and I’m going to use two double quotes, so it should look like that. Make sure you don’t use single quotation marks like that. That’s not what we want. We want double quotation marks like that, and inside of there, we’re going to type in the words Hello and World. Make sure that you have an open parenthesis, a double quote, the words Hello World, then another double quote then another parenthesis, a closing parenthesis, and then at the very end of this line, I’m going to use a semicolon and it looks like that. It’s not a colon and it’s not a comma. It looks like that. Then I’m going to use the Enter key on the keyboard to go to the next line, I’m going to type in Console.ReadLine opening and closing parentheses. Now you may have noticed that as you type in the opening parentheses that Visual Studio will automatically type in a closing one for you. You don’t let that throw, you can continue just to type through that, but make sure that you have exactly what I’ve typed into my code window here for these two lines of code. Make sure that the capitalization is correct. Make sure that you’re using a period not a comma for the little mark that comes after the word Console. Make sure you’re using parentheses and not some other type of bracket, or brace, and then make sure that both lines of code end with a semicolon. The next thing that I want to do is save my project, and there are a number of different ways to do this in Visual Studio. Again, I keep it simple and go to File, Save all. Then the next thing I want to do is now see my application actually running. To do that, I can either find this little green triangle that has the word Start next to it or if I don’t see that by default in my little toolbar here at the top, I can go to Debug and select “Start Debugging.” Either way should work. I’m going to go ahead and click that, and you’ll notice that some windows pop up and Visual Studio changes its appearance a little bit. Now, off to the side of my screen, the console window popped up and we see the words, Hello World with a blinking cursor below it. I’m just going to hit the Enter key on my keyboard and then the console window disappears and I’m back and the Visual Studio resets itself and we’re successful. However, maybe your experience wasn’t successful. Maybe you saw an error message, so what I want to do is take a moment and look at some common errors that people that are new to C-Sharp might run into and how to remedy them and this is a good opportunity to learn some of the syntax rules of C-Sharp as we make mistakes. I’m going to pause the video, make a mistake, and then we’ll talk about it, pause it, and so on. When you attempted to start the application, you may have seen a little dialogue pop up from Visual Studio that says, “There were build errors. Would you like to continue and run the last successful build?” Always select no for that. What you’ll see next is a list of errors. Now, in some cases, the error messages will be obvious to you, and they’ll make a lot of sense. Sometimes they won’t. Like the verbiage might be something we’re just not familiar with yet. Invalid token and class structure interface, what does that mean? Typically what you can just do is double click on these and that’ll put your mouse cursor on the line where the problem is. Notice that Visual Studio also gives you another visual way to tell that there’s a problem with your code. Gives you these little red squiggly lines. Sometimes you see a blue squiggly line. They’re a little bit different but essentially this is an area of the code that probably deserves your attention, something you need to fix. Now, in this particular case, the problem is that we didn’t type our code in between the innermost opening and closing curly braces and so this is an issue with regards to defining a code block in C-Sharp or a block of code. Different C-Sharp commands belong in different kinds of code blocks, and I’m going to spend a lot of time in this course talking about the different types of code blocks and what belongs in each type of code block. But to remedy this issue, what you need to do is use your mouse and just drag and highlight these two lines, or you can use the Shift key on your keyboard in the arrow keys to highlight that area hit Control X, then move up in between the opening and closing curly brace and paste Control V that code in there, and then it should run correctly at that point. That teaches us the first thing about C-Sharp. It matters where we type our code. Or when you try to run the application you may have seen the same build error dialogue, except you see the message, “Semicolon expected.” Hopefully, this is an obvious remedy for you. If you double click on that error in the error list, it should take you to the end of the line of code where you forgot to add a semicolon. That’s the second thing about C-Sharp that we’re going to learn. Is that just like a properly formed English sentence has to end with a period or a question mark or an exclamation mark, a properly formed instruction in C-Sharp has to end with a semicolon, or maybe the error that you saw was something like a syntax error, something expected, the name Hello doesn’t exist in the current context. The name World doesn’t exist in the current context. If you were to double click these, you’ll get to the vicinity of the problem and you’ll also see that there’s red squiggly lines beneath the words Hello and World in between our parentheses. Now, remember, we needed to use double quotation marks around that string of characters Hello World and so alphanumeric characters that we want to literally write to screen, or present in some way, we need to surround them with characters that indicate that we want to use this string of literal characters. To do that, we use double-quotes. Or perhaps you see the error, something like, “The name console does not exist in the current context.” You look at the word and you say, well, looks spelled correctly. Remember that I told you you had to type exactly what I was typing and so C-Sharp is case sensitive, meaning that a lower case C and an upper case C mean that you’re typing two completely different things into C-Sharp and that is tricky because many of us are not used to that degree of precision whenever we’re communicating. But when communicating with a computer, you have to be precise. In this case, all we needed to do was change the capitalization of the word console and we’re back in business. Perhaps you see something like console does not contain a definition for either write line or read line, and again, you’re looking at it and you’re thinking it’s spelled correctly. Well, what could the problem be? Here again, capitalization is important. r read line is different than R read line, and l read line is different than L read line. Again, things have to be spelled correctly and have the correct capitalization in order to be processed correctly by the C-sharp compiler. We’ll talk about compilation in the next lesson. Now, if you’re not good at spelling and you’re not good at typing in capitalization and you’re just not as precise in the way that you would type a letter or an e-mail message or even a text message, fortunately Visual Studio can help you out. There are tools that will help you not only write your code more quickly, but also more accurately. If you utilize those tools, the chances that you will miss some of these really simple syntax things like capitalization, will almost be completely eliminated. We’ll talk about some of those tools in an upcoming lesson. All right, but assuming that you got all of this to work correctly, you’re really well on your way to building applications, you’ve already crossed over one of the big first steps. As you undoubtedly learned in this lesson, writing C-sharp code is an exercise in precision. Again fortunately, the Visual Studio IDE will help you out a lot when it comes to that. It will give you clues and maybe some of the phrases in the words that they use to explain the issue might not be familiar to you. Yet with experience, it will be. But generally, it’ll point you into the right direction and with the red squiggly lines in the message, you can typically figure out what the issue is. Now throughout this course if you run into a wall and you simply can’t figure out what the problem is, do this. Compare character by character, take your time until you develop a vision for the problems where your eye will jump to the problem and code. Compare what you wrote versus what I wrote. I’ll supply the source code to you. Open it up in a second copy of Visual Studio and then just look character by character. What did I do different than what Bob did? That will usually help you figure things out if you can’t do it on your own. In the following the lessons, we’re going to focus on two things. First of all, we’re going to talk about why we did what we did and what was going on behind the scenes that turned our code into a working application, all be it a small application. What happens whenever we create a new project? What happens whenever we choose to save our project? What happens whenever we choose to start or run our applications? Then secondly, we’re going to talk about the syntax of the C-sharp code that we wrote, and we’ll learn more syntax rules and more keywords as we go along. If precision is so very important in C-sharp, then you’re going to need to have some explanation as to what all those little words and symbols actually mean and some rules to guide you as you’re writing your own code. It’s really easy once you get a few of the basics under your belt. Being completely honest, many people learn how to write code in C-sharp. It’s a fairly easy language to learn, you can do this. Just you got to put a little bit of time, a little bit of effort to figure it out. We’ll begin that process in the very next lesson. Will see you there, thanks. Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. Now in this lesson, we want to start the process of dissecting that little application that we wrote in the previous lesson. Now previously, I wanted you to focus on the workflow. What we did and how we did it. But now what I want to do is focus on why we did what we did. It’s really crucial at this point that we cement some really important ideas in your mind because they’re going to provide the basis, the foundation for everything that comes next. What I want to do is start on the inside and work our way out. I’ll start by talking about the nature of writing code. When you learn how to write applications with C-sharp, really any programming language, learning the syntax of C-sharp or in other words learning the nouns and the verbs and the punctuation of the programming language is really just half the battle. The other half of the battle is learning about related, pre-built functionality that’s available to the code that you write. Now in our case, Microsoft has created something called the .NET Framework, which sounds spooky and mysterious, but it’s really not that bad. It’s actually pretty large, but we’re only going to focus on two specific portions of it for our purposes. The first part that I want to focus on is something called the class library, which is simply just the library of code that Microsoft wrote to take care of difficult tasks so that, as software developers, we don’t have to worry about them. There’s library code to help with many common things that many applications will need, things like working with math, or working with strings and text, and working with dates, manipulating dates and times, maybe displaying things to the computer screen or transmitting information across a network. A lot of that foundational stuff that would be difficult for us to write and is utilized by many different applications. That’s really the first part. It’s taking advantage and understanding the class library of the.NET Framework. The second part of the.NET Framework is called the runtime. It’s also known as the common language runtime, you’ll see it called as the CLR as well. Really, it’s just this protective bubble that wraps around your application. Your application lives inside of it. It runs inside of that protective bubble and it essentially takes care of a lot of the low level details so that you, the software developer, you can focus on what your application is supposed to do, not worry so much about how it’s actually accomplishing it under the hood. You don’t have to worry about the computer’s operating system, interacting with it, and interacting with memory, and interacting with the hardware, the computer itself. Many of those things are abstracted away from you. You don’t have to worry about them. Furthermore, the seal are that runtime also provides a layer of protection for the end user so that you, the malicious evil software developer, you can’t do something really bad to somebody’s computer without them at least giving you permission to do it in the first place. So without their knowledge and their approval, you’re not going to be able to wipe out their entire hard drive, for example. For right now, it’s the.NET Framework class library that I really want to focus on because it’s what we used, whether you realize it or not, whenever we were writing our first application. For example in line 13 or 14 where we did our work, you see Console.WriteLine and then we used open parentheses, close parentheses, and so on. We were using code in the framework class library that knows how to display text into a console window. All we got to do is say hey, use this text, stick it in a window. We don’t really care how it does its job, we just care that it did it. The next line of code, this console.ReadLine. It was also really important. We’re telling the application to wait for input from the end user before continuing its execution. Again, here we’re calling code in the.NET Framework class library that knows how to accept user input. You recall that I use the “Enter” key in the keyboard, and then the application continued on. It exited and we were back in the Visual Studio. So in both of those lines of code, we were utilizing methods that were created by somebody in Microsoft to handle that interaction with displaying and retrieving data from the end user. What were to happen if we were to comment out that line of code? Here to comment out of line of code, I use two forward slashes on my computer, it’s over the question mark. Commenting our code simply means that I want those instructions to be ignored. Now, I could have just deleted that line of code completely, but I might want it later. Maybe I don’t want to remove it completely, I just don’t want to ignore it for now. I also might use code comments to write myself some notes to remind myself of something about the application in the future. We’ll talk about code comments a little bit later. But if we were to run the application now, watch what happens. It ran and it’s already done. What happened? Well, you may have seen a flicker on screen for a fraction of a second. The reason was because, hey, it executed this one line of code and it said looks like I’m done here, and it exits out of the application. By adding the read line, we’re now stopping execution, waiting for the end user to do something before exiting out. Hopefully that makes sense. All right, so next let’s talk about the position of the code that we wrote. I made sure to emphasize that you have to write the code in the correct place, and the correct place was in between the opening and closing curly braces of that innermost set of curly braces as defined by the level of indentation that we saw in the boilerplate code. If you don’t add the code there, we saw what the ramification of that was. The application, you’ll try to run it. It’ll give you a runtime error. The correct place for that code was where we have it right now, in between that opening and closing curly brace that you see on screen. Now as you can see, there are several sets of curly braces, and so it’s important that we talk about what these do. I need to oversimplify things here. We will come back and fill in some of the details later. But essentially, you have an opening and closing set of curly braces and those define the code block. Code blocks typically have names and they have purposes. In this particular case, we have a first code block and this code block has the name Main. This particular code block is known as a method, and this particular method by convention is the very first method that’s called whenever your application is executed. I don’t want you to worry about these other words static and void and even the string and the args for right now, we’ll talk about those later on. But this entire code block here, as well as the line above it, they define something called a method. A method is simply a block of code that has a name. Now, later on, you’re going to come to realize that a method is so much more than that. But I want to use that as a working definition as we’re getting started here. The method has a name, and when you have a name, you can call a name and say, I want you to execute. We’ll talk about methods again a little bit more a little while. This main method lives inside of another set of curly braces, and that set of curly braces also have a name. The name is program, it’s a class called program. You can think of a class as simply a container for all of the methods of your application. You can keep the methods that are related to each other in separate classes. Now what do I mean by related to each other? Well, that’s really for you the developer to decide as you get deeper into programming, you’re going to come to understand the thought process behind organizing your code. But that’s a little ways off for now. Just trust me on that. Now I said that a class was merely a way to organize your methods. It is so much more than that. Again, I’m way over simplifying this as we’re getting started here. But the main takeaway for right now is that code is organized in curly brace containers and you have some blocks of code that reside inside of other blocks of code. To emphasize that again, here we have another set of curly braces, and this set of curly braces has a name as well. In fact, it’s a namespace called HelloWorld, which happens to be the name of the application that we gave it. Again, key things extremely simple here a namespace is just another way of organizing code again. At some point it becomes so much more than that, but let’s keep it simple for now. Let’s take a look at these lines of code and illustrate these ideas about classes that contain methods. Here what we’re doing whenever we’re calling Console.WriteLine is we’re actually making a call into the dotNet Framework class library. Remember, it’s that library of code supplied by Microsoft. We’re saying in that entire library there’s a book and there’s a chapter inside of that book that I want to reference. In this case, we’re saying, that book is the console book, the class. I want you to look at the chapter named WriteLine that has the definition for this method. Hopefully, that analogy works for you, but we’re looking inside of a library to find a class, and we’re going to call a particular method inside of that class. By using its name, we can execute all the code that was written inside of that method. Same with the method that we’re calling below it as well. Notice that there is a period that we use between the name of the class and the method name, and we use that. It’s called a member accessor it allows us to access a member of the class or in other words, now that we know what the book is, we can find out what chapter we want to reference. Hopefully, that analogy works for you. Now, notice also that both whenever we call the WriteLine method and the ReadLine method, that they both have parentheses following them. Now, in the case of the WriteLine method, we’re actually sticking something in between the opening and closing parentheses, whereas in the ReadLine method, we’re not. But essentially, those parentheses are saying, not only do we want to reference that particular class method name, but the parentheses mean I want you to actually invoke it, execute it, do it now, so that’s the purpose for those parentheses. Now we can say, do it now and pass in information. Do it now with this stuff, with this argument. We’re passing in an argument to the WriteLine method and saying, we want you to do it right to screen and here’s what we want you to write. It’s an input parameter to the method named WriteLine. Now don’t worry, we’re going to come back to the notion of methods in the future, as well as passing values into a method like we did and as we passed in the literal string HelloWorld into our method here. Just know that whenever you see parentheses after a given word in your code, you should be thinking that code is being called right now as we step through the execution of the code. Next up, let’s talk about the semicolon. We’ve already explained it in the previous video, but just to emphasize it. Notice that almost everything, even these statements at the very top have semicolons, with the exception or whenever we’re defining a namespace, a class, or a method. We said at the time that the semicolons are actually similar to the period or exclamation mark or question mark at the end of an English sentence. It completes a thought in C-Sharp. Now, some programming languages like Visual Basic, for example, they don’t really have this idea. They only allow one complete thought per line of code. However, with C-Sharp, you could do this, what I’m about to do watch. Now I have both of those lines of code on a single line. If we run the application will work just as it did before. The way that you separate or indicate that you have two different complete thoughts, is through the use of a semicolon. Furthermore, we could put lines of code on separate lines like this. Now, it wouldn’t make sense in this case because the line of code is so short, it actually makes it difficult to read. But sometimes when you have a very long line of code, you’ll see me split that line of code into multiple lines, and still the application will execute. Now, in other programming languages, you wouldn’t have that behavior. Because really whitespace in line feeds and things of that nature, they don’t matter to C-Sharp. The only thing that really matters is to indicate a complete thought is a semicolon at the end of the line. Let me go ahead and get rid of all that. The other thing that I want to mention here that you may have noticed is the level of indentation that you get automatically from Visual Studio. Now that’s completely optional, and Visual Studio nudges you in the right direction. But essentially, even if you were to come out here and we’ll use the tab key several times and write the word Console.WriteLine, something like that. Notice that Visual Studio reinvented it for us. Why do you suppose it did that? Well, many people believe that indentation helps the readability of the code so that you can see what code container where code resides inside of the other curly braces inside of your application. Along those same lines for readability sake notice that there are many different colors that are used as text inside of this text editor window. You have these royal blue colors, and these are my default colors. Yours might look a little bit different, but by default, I think you have some royal blue, some black. You have aqua color here. This is a dark red. You have some light gray and light blue. All of those are used to help you identify the parts of speech, I guess you can say inside of the code that you write. We’ll talk more about that as we talk more about the syntax of C-Sharp in an upcoming lesson. Now that we’ve talked about the code that we wrote and its position and formatting and whitespace and tabs and all that stuff, what I want to do is stop right now for this video and in the next one, I want to talk about the files themselves. The file that we typed our code into, how that relates to projects and even solutions. What happened when we saved our project? What happened when we actually ran our project? We’ll do that in the very next lesson. We’ll see you there. Thanks. Hi, I’m Bob Tabor with Developer University. For more my training videos for beginners, please visit me at EW.com. Next, we’re going to talk about how code files are organized into projects and solutions. Then where you can actually find these projects and solutions on your hard drive. Whenever we created a new console project, the program does see a file was opened for us automatically in the main area in Visual Studio. That’s one of the things that project templates do for us whenever we choose File, New Project and we see the new project dialog and we choose a project template. They provide a great starting point for the type of application that we want to build. It includes files with boilerplate code, important settings and other resources that we might need whenever we’re building that type of application. As you can see, we’re working inside of this file in the main area and there’s a series of tabs. Again, this is an intended to be an overview of Visual Studio, but it’s important to note that the names of the code files that you’re working on are contained inside of those tabs. If you take a look over to the right hand side, here is the solution explorer window. It has a tree like structure of all the items that are contained inside of our projects. Now again, as I said at the outset of this course, this isn’t intended to provide a tour of Visual Studio per say. There are other resources on Microsoft Virtual Academy that can really help orient you to using Visual Studio in the various Windows and functionality that it contains, but the solution explorer is probably the most important part of Visual Studio next to this main area, where you’ll usually see the text editor and other designer windows. Simply put, the solution explorer is our main navigational device to the other files and settings that comprise our program. You can see here that there is a program, that cs file. Now, if I were to close the program, that see us tab in the main area, I can always get back to it and open it up again by double clicking it inside the Solution Explorer. You can see it’s open once again. The files and important settings are organized into a concept called projects, so you can see here this word “Hello World” is actually a project. You can see there’s a little C-sharp icon next to it, letting us know that this is a C-sharp project specifically. Projects get compiled into a single.Net assembly, which we’ll talk about later. Furthermore, one or more projects are organized into solutions, and you can see in the Solution Explorer, we have one solution here at the very top solution also named HelloWorld that contains one project. Now, in many cases, as you’re getting started, you’re only going to have one project inside of one solution. But as you come to build more complex applications over time, it’s highly likely that you’re going to need to manage multiple projects that are somehow related. Now again, the reason might not be obvious at this point, but as you continue to learn C-sharp and how to build more complex applications for large companies or for yourself, this becomes a crucial code management strategy. But just for now, accept the fact that there’s this extra layer of a solution and one solution can contain one or more projects and the projects will contain then all of the code files in the settings and the like that will be used to create an actual executable program. Trust me, these concepts will become more important after we get past the basics. Now, the big question at this point should be, where are all these projects and solutions and files actually stored on your hard drive? I mean, can we see them? We can see them in the Solution Explorer. Where are they actually on your hard drive? Well, when we created this “Hello World” project, we merely provided the name of the project, you’ll recall. Then I said, go ahead and accept the other defaults. By default, Visual Studio will put your projects into your documents folder. If you take a look here and we navigate into the documents folder, it will put your projects into whatever version of Visual Studio you’re currently using, so you can say I have side by side Visual Studio 2013 and 2015. We’re using 2015 for this series, but it could be a future version of Visual Studio. You’ll look in that particular folder for your version of Visual Studio. As we drill in, there will be a projects folder and as you drill and you can see that by default, when we created a new project, it put it here in our document slash visual studio, whatever version slash projects folder. As I add more projects, this obviously will be filled up with folder names for those projects. It’s important to note that whenever you create a new project, you don’t have to create it and put it right here. You can put it anywhere. To keep things organized, you’re typically going to keep them in the same place. Now, furthermore, you can actually open up a project that saved anywhere on your computer as well. For example, in this course, I’ll supply the projects. After I record the video, I’ll zip them up and you’ll be able to download them and then open them up on your own hard drive and then walk through them and to better understand them. Just to demonstrate how you do this, I have this project zipped up into a file called example.zip. What I’m going to do is actually right click this and select Extract all, and then in the extract compressed zip folders. I’m just going to put this on my route. C;/Example, and then click “Extract”. Now you can see that on my local hard drive I have an example folder. Inside of that folder there is another folder with a file called Example.sln, I’ll talk about that in just a moment. But I can either double click this.sln file to open up the the solution inside a visual studio, like so. Or I could go to “File”, “Open”, “Project/Solution”, and then navigate to that directory using the open project dialog if it’ll let me. Unfortunately, it’s a little bit too large for the recording area, but then I would just simply select the solution that I wanted to open from this dialogue and then click the “Open” button. Let’s go ahead and close that, and let’s shut down this copy of Visual Studio. I want to get back to where we were just a moment ago in our Documents, Visual Studio, in my case Visual Studio 2015 Project folder. Here are a list of all the solutions in our Project folder. Just want to walk our way through this. This first folder here will contain our solution files. There’s this.sln file, which is a solution file that contains information about all the projects, that are under this umbrella solution. We could actually open this up and look at it inside of notepad, and it’s simply just a configuration file. There’s nothing all that special about it. You certainly don’t want to make any changes to it, but it’s going to have information about all of the locations for the various projects that are associated with this solution, any global settings and some of these things won’t really be useful to us until we get deeper into our understanding of compilation and things of that nature. But inside of the solution folder, is a second folder which is actually going to contain the project files. Here we have a HelloWorld.csproj, which is the C-sharp project file. Let’s open that up as well with notepad. It’ll contain references to things like all the files that are associated with this project, any of the settings and any other metadata. Again, information in here that you certainly don’t want to edit, you don’t want to accidentally make any changes to it whatsoever. But I just wanted to make you aware of it, that there’s really nothing magical going on. There’s just these configuration files that contain information about your project. As you make settings on the project level, those will be saved inside of that cs project. Then finally, there’s this bin folder here. The “Word” bin typically is short for binary, which denotes that this is where a binary version of your application will be stored. The process of compilation it takes your source code, which is human readable, and it’s going to convert it into a format that is machine readable, or understood by a machine, your computer. If we were to take a look inside of this folder, we would see that there is a debug folder. This folders created for us whenever we started debugging our application, it creates a temporary version of our application for debugging purposes, which we’ll talk about later. If we drill into that you’ll see that there is actually an executable file and several other helper files for the purpose of debugging. We’ll talk about these later. If I were to double click the HelloWorld.exe, it actually executes our application. Compiling your code into a working application is the end goal. But I don’t want to talk about compilation just too much yet or about creating a debug version versus a release version of your dotnet assembly of your compile code. I think you’re going to get a better appreciation for those ideas, after we get past some more of the basics. What I want to do is stop our conversation about the directory right now. We’ll come back to that a little bit later. But you’re doing great. Let’s continue on. We’ll start learning more C-sharp now that we have some of these tangential topics all the way. I’ll see in the next lesson. Thanks. Hey. I’m Bob Tabor with Developer University. For more my videos for beginners, please visit me at Devu.com. Now in this lesson, I want to get back in to talking about C-sharp the syntax. We’re going to talk about declaring variables, how to choose the right data type, for your new variable and then also how to initialize variables with values. To begin, let’s take a look on screen. If you’ve ever taken an algebra course, hopefully you’ve seen something like this, where you’re asked to solve for the value of x, and hopefully without a lot of thought, you’re able to see that x equals 7. Using that same thought process, take a look at this little snippet of code on screen. x equals 7, y equals x plus 3. Then we’re going to do a console.WriteLine with the value of y. Hopefully you look at it for a moment, using your existing knowledge of algebra and you think to yourself, then it’s going to output the value of 10 to a console window, right? Exactly. So my point is that C-sharp, first of all, is human readable. It’s got a few things that might be a little formed like the semicolon at the end of the line. However, for the most part, I’m willing to bet that as we go through the series of lessons, you’ll be able to understand what the code is doing for the most part. Even before I explain it to you. It’s really not that hard. Then secondly, it’s probably very similar to things that you’ve done in the past like working with math and algebra and things of that nature. If we’re looking at the C-sharp code, the x and the y in this context, are referred to as variables. A variable is simply under the hood, a bucket. I guess you could call it in the computer’s memory and you put things in buckets and you dump things out of buckets. We can put values into a given bucket in the computer’s memory, and we can retrieve the value out of that bucket. We can even replace what’s in the bucket with something different. That is what you use a variable for. This particular situation that we see on screen, these buckets are just holding numeric values. However, we could create buckets that are just the right size for almost any type of information, whether it be individual alphanumeric characters, or strings of character, strings of alphanumeric characters like even entire sentences and paragraphs, and even books. We can also create buckets that are just the right size for dates and times, buckets that are just the right size for really, really, really massive numbers, or even create buckets that are just the right size for numbers that have a lot of values after a decimal point. Now, in this case, what we would expect to see here is that these two buckets, the bucket that’s labeled x and the bucket that’s labeled y, would hold numeric values. Because we want to add numeric values together. We know that. But how do we express that intent in C-sharp? The instructions that we write in C-sharp were ultimately after a compilation step, they will ultimately be executed by the dotnet runtime that we learned about in a previous lesson. In part its responsibilities are to make sure to allocate memory for our variables in memory to hold the right kind of data. Here we have two data items, are x and y, and we have to tell the runtime that we want to allocate some space in memory that sufficiently large enough, to hold numeric data, like the type of data that we want to work with here and our application. But how do we do that? Well, that’s the topic of this lesson. To get started, what we want to do is create a new project. Here again, I’m going to go to file, new project. We will go to the new project dialogue and make sure we select the Console Application project template. Here we’re going to rename this and call this project variables and then click the “Okay” button. Visual Studio goes to work, uses that template and creates a new solution with a project and as you can see on screen here we are back in our familiar program.cs. Obviously we want to work inside of our static void main in between the opening and the closing curly brace just like we learned about in our previous lesson. Before we get started, there’s one big takeaway from this lesson and that is that a variable is simply a bucket in memory that you can put data into and retrieve data out of but we have to tell the compiler, we have to tell the.Net runtime what size of buckets that we want to create. We have to declare our variables, we have to create those buckets and then give them some label that we can refer to them with from that point on. Now, before we get started here typing some code, all the same rules apply in this video that applied previously. You have to type the code exactly the way that I type it. Take the time, develop the skill of identifying even small differences, different in capitalization, or spacing, or the various special punctuation marks that we use while we’re writing code. Develop that skill to identify the differences between what I write on screen and what you’re writing in your copy of Visual Studio. If you see a little red squiggly line, you already know that there’s going to be a problem there. That gives you the clue necessary to go and focus either on that exact character or in that vicinity and use your detective skills to figure out what it is that went wrong. Now let’s go ahead and we’re going to create two buckets, two variables and define them in such a way that they’re going to hold numeric values. We’ll start with int x and int y as simple as that. Here to borrow the explanation that we used earlier, we are asking the.Net runtime to allocate space in our computer’s memory sufficiently large enough to hold numeric values. Now, we’re asking it to create these two buckets and eventually we’re going to put values into them and read values out of them but at this point we’re just declaring their existence and saying, here’s what we need to work with. Then after we’ve declared that, after we create them in this manner, then we can begin to work with them and assign values, retrieve values from them. But most importantly here I’m telling the computer that I want to assign integer values into those variables. An integer is really just a mathematical term that refers to a whole number that’s within a certain range. No values after the decimal point and as far as C-sharp is concerned, the values have to be between a negative two billion, 147 million and a positive two billion,147 million. That’s the size of the bucket that we have to work with. If you need to work with much larger numbers then the in data type is not the correct data type for you, there are other data types to choose from and we’ll learn about some of those a little bit later. If we need to work with like money values where you have dollars and cents or pounds and pence, then the integer is not the right data type to work with. Let’s continue in our application and this is basically just to continue what we did in Notepad a few moments ago. X equals seven, y equals x plus 3, and then we want to do a console.write line with the value of y. Then remember we want to do a console that read line so we can actually see it on screen without it just flashing and going away immediately. Let’s run the application and make sure we get the value that we’re expecting. Hopefully you got the value 10 in your copy of Visual Studio just like I got in mine. If not, again, make sure you double check your work against mine. After we declared the variables in lines 13 and 14, then in lines 16 and 17 I’m doing assignment using the equals sign. Now, in this case we don’t really call it the equal sign, we call it the assignment operator. We’ll learn about operators in the next couple of lessons. This particular operator, the equal sign means take whatever is on the right hand side and assign that into whatever is on the left hand side. We’re going to say give me the value of seven and assign that to a variable, a bucket named x. The same thing would be true here with y, we’re assigning a value into the bucket named y but we have to do something interesting here. We have to actually retrieve the value of x from memory. Where’s that bucket again? Oh, there’s the bucket, dumped the value in the bucket out, you’re holding the value seven. Add that to three and then we assign that to the value of y. Now, here we’re retrieving the value of y saying, give me the bucket with y in it and you dump it out into the console.write line which we know, then we’ll print that to screen and that’s essentially assignment and retrieval of variables. This is a very simple case. What I want to do now is comment out this code. If I were to begin commenting out the code like we learned about in a previous lesson, I could use the two forward slashes. I’m going to show you a different method in just a moment but notice when I do that, something interesting happens. I commented out the declaration for the variable named x. When I do that, notice these little red squiggly lines underneath x’s and if I hold my mouse cursor there, it says the name x doesn’t exist in the current context. We might say, well, there it is right there. It’s in our code comment, but remember we’re telling the the C-sharp compiler and ultimately the .Net runtime to ignore that instruction. The compiler is looking at our code and saying, I have no idea what you’re talking about X. I’ve never heard of X before, I don’t know what you want me to do with X, and so it raises the red flag and say, I can’t continue on under these conditions, you have to give me more information. Obviously we can fix it by removing the code comments. Now, what I want to do is comment out several lines of code and instead of just doing two forward slashes in front of every line which can be laborious, I’m going to comment out multiple lines at the same time using a forward slash and a star character over the number 8 on your keyboard to begin a lengthy comment. Then right here before that read line, actually let’s go ahead and keep it all together. After that I’m going to do a star forward slash. Now we’re going to type another code example beneath that. This will be a little bit more interesting. Follow along. Pause the video if you need to catch up with me, I’m going to try and type fast just to save time. Before I forget, let’s go “File”, “Save All”. Now let’s begin here at the top. You can see that this is a different style application with some different commands or different uses of commands that we’re familiar with. We’re just going to play a little name game and we’re going to ask, what is your name, and we output type your first name. Now notice in the first case, I’m using a right line, which will print what is your name to screen and then use a line feed character to go to the next line. However, I’m using yet a third method from the console object, the console class, which we’ll talk about classes and methods later. But this method is different than write line. This will just write out the statement type your first name, whatever’s in between our double quotes there, and it won’t go to the next line. It’ll just wait there on that line. Then what we’re going to do is create a new variable using a different data type, a string data type. We’re not interested in individual alphanumeric characters, so a-z, 1-0, and the special characters. We’re interested in a string of them or a collection of those characters. So not just the individual character B, the individual character O, and the individual character B, we’re interested in them as a string or a

    collection as Bob B-O-B. That’s what we’re declaring a bucket in the computer’s memory sufficiently large enough to hold a string of characters, however long that it is. Then what I’m doing is calling our Console.ReadLine method that we’re already familiar with. But there’s a twist on this. Up to this point, we said we’re using the ReadLine method in order to stop the execution of the application to wait for the user to hit the “Enter” key in their keyboard, then to resume. However, now we’re using it for its real intent, which is to retrieve data from the end-user. In this case, we’re asking the question, what’s your name? The user types it in and hits “Enter”, and then whatever they typed in is assigned using the Assignment operator to the variable we created called first name. Hopefully, that makes sense. Now we’re going to create a second variable of type string called my last name. We’re going to do the same thing here, Console.Write, and then we’re going to allow the user to type in their last name, and then whatever they type in when they hit the “Enter” key on their keyboard will be saved or assigned to the variable called myLastName. Now that we’ve done assignment to my first name and my last name, I’m merely going to concatenate the values together. Let me point something out. There are several things we need to talk about here. Notice here we were doing actual math where we were adding values together. This is the arithmetic or arithmetic operator. We’re basically adding things together right here. We’re kind of adding things together, but that connotation is different. We’re not adding Hello and Bob and Tabor with some spaces in there. From a mathematical perspective, we’re concatenating strings of characters together to make one really long string. It’s the same operator, but it’s used in two slightly different contexts. Kind of does the same thing, but we need to understand that there’s a fundamental difference in how operators interact with different data types. You’ll see why this is important as we continue on through this course. But at the very end here we’re expecting to see, Hello, Bob, notice that I have in here a additional double quote with a space in between to give some space in between the first name in the last name, and then obviously, my last name here. We’ll get that one more line of code to write because we need to do another read line so we can see the value on screen. Let’s run the application. Then we have some things we want to talk about here. What is your name? Type first name Bob, Enter, type your last name, Tabor, Enter. Hello, Bob Tabor. Awesome, so very simple application, but hopefully, now we’re pushing the envelope a little bit more, learning a little bit more about additional data types that we can use for our variables and learning about assignment that it works with all kinds of variables, and then also learning about operators that work differently with different data types. Now, before we get too far, in the previous example, we used merely X and Y, which we might expect to see in some mathematical context because we’re used to seeing those characters used in algebra problems. But whenever we start writing business applications or even games, we need to give our variables names that are meaningful inside of the program that we’re writing. I could have just called this x and then done something like this x and then done something like this x, and you’d look at this and you’d say, I have no idea what x is supposed to do. It’s because we used a very vague description of the bucket in the computer’s memory. Instead, you don’t have to worry about keystrokes, make it human-readable. Write your code in such a way that somebody can read through it and understand exactly what the variables are doing and what the logic of the application is doing. Then also notice as I go and change some of these things back here to my first name, I used a little feature of Visual Studio that allowed me to say, now that I have changed the name of x to first name, let me rename it everywhere that I’ve used the word x. Did you notice I did that? I hit the “Control” and the period on the keyboard here. Let’s do that one more time. I’m going to change this back to x. Notice that I get a little light bulb here off to the left-hand side, which is Quick actions, and then I hit “Control” period on my keyboard. Now it gives me the option to rename my first name to x and it even off to the right-hand side shows me all of these changes. This is called a refactoring. I’m changing the code just ever so slightly by renaming things to give them more meaning. In this case, I’m doing the exact opposite, but we’ll come back to that. Do I want to rename every time I use the variable name, my first name to x? Yes, so let’s rename everything bam just like that. Let’s rename it one more time. So myFirstName, Control, period, and now I want to rename everything from x to myFirstName. You might look at that phrase, myFirstName, and then again, I used it down here, myLastName, and you’re thinking yourself, that’s a crazy naming convention. Well, it’s a naming convention that’s called camel casing, where you start with the first letter in a list of words that you’re munching together to describe a variable or something along those lines. Use a lowercase for the first letter of the first word and then an uppercase letter for the second and subsequent words in variable name. Ideally, it makes it human readable. I can read it fairly easily that way. At this point, I think it’s important also to do something like this. I’m going to rename this to myfirstname all lowercase. Remember what we said in the previous video that C# is a case sensitive language. So if you were to use the wrong capitalization, then you’re going to get a red squiggly line and it says my first name does not exist in the current context. Do you remember seeing that just a moment ago when we removed the declaration for x up here when we commented it out? The same thing is true here. Myfirstname, all lowercase is different from the variable defined called my F Name, First name. Capitalization matters. Make sure that you remember that. In this case, let’s just go ahead and change everything back correctly, and we should be good to go again. Great. Now you might be saying to yourself, well, this degree of precision seems pretty difficult. How am I going to remember exactly what I named things in the past? There are a couple of different tricks for them. Keeping your code and methods small, and we’ll talk about that later, that’s one way to do it. But then the other thing is to rely on IntelliSense, which is that little code window that I told you to ignore before. It’s actually pretty important. As I start typing my, notice that it pops up beneath what I’m typing, the correct capitalization, correct spelling for any of the variables that I’ve defined up to this point that start with the letters m, y. Now, at this point, what I can do is simply hit the equals sign on my keyboard and it will type everything else out for me. So I don’t have to worry about spelling, I don’t have to worry about capitalization. You may have noticed while I was typing, I was typing and then using arrow keys on my keyboard, and then you couldn’t really see my fingers moving, but I wasn’t typing every single keystroke. This is what allows software developers to write code very quickly. Once you get used to relying on IntelliSense, one of the tools that Visual Studio gives you in the text editor to make your typing more accurate and allow you to type much faster than maybe you normally could. We’ll come back to IntelliSense later. The other thing that I wanted to tell you about here or talk about is that we cannot define the same variable two times. Let’s try this. I’m going to go and view myFirstName and say I want another bucket in the computer’s memory with the same name, myFirstName, and the compiler says, you can’t do that. We’ve already got a bucket. We’re going to confuse buckets in memory if we give two buckets the same name. it says a local variable name, myFirstName, is already defined in this scope. You can’t do that. Now we could do this, but I highly recommend you don’t do that because, again, myfirstname all lowercase is different than my first name with camel case. But this would cause a high degree of confusion, so never do that. Be descriptive with your variable names, don’t repeat variable names, always stick to a naming convention, and never break that rule. If you follow those little rules, I think you’ll find some of these initial issues they’ll just dissipate, you won’t have to worry about them. What I want to do now is take a look at this second set of code. Then not only are we in line number 29 declaring the variable, but then in line number 31, we’re actually giving it a value. What if we were to rewrite this little passage of code? I’ll go ahead and comment all of this out, and I’m going to make this smaller. In fact, here’s one we’ll do, string myLastName equals Console.ReadLine, and then I will say above that Console.WriteLine, “Type your last name.” You can see that I took these two lines of code 29 and 31 and I combined them together. What I’m doing here is not only declaring the variable, but then I’m initializing its value to whatever we retrieve when we call Read Line. This is called initialization, and initialization is important because you want to give your variables a value as quickly as possible. This puts your variable into what’s called a, valid state, which will be an important idea as we learn to write real applications. But also experienced developers like to write less code, and they’re always looking for a convenient way to reduce the number of keystrokes that they have to type and reduce the amount of code that they have to read. Usually you want to declare your variables as you’re using them and not declare them like some people used to do a long time ago, put them all at the very top of a given method or or section of code. You should get into the practice of two things, declaring your variables as you need them in the body of your code, and then secondly, if you can, give them an initialized value immediately after you declare them, like we’ve done here in line number 34. Tell you what, let’s stop right there. I think we’ve covered a lot of ground for one lesson. Let’s do a quick recap and just talk about over a dozen things that we discussed. We talked about what a variable is. We talked about how to declare a variable, how to choose the correct data type. We talked about the int data type and the string data type. We talked about assigning values into variables and then retrieving values out of variables. We talked about the assignment operator. We looked at the arithmetic operator and also the string concatenation operator, which is both just the plus sign. We looked at Console.Write versus Console.WriteLine. We looked at the other life of the Console.ReadLine method that we can actually retrieve the values that the user types in. We talked about camel casing and naming conventions for our variables. We looked at IntelliSense. We talked about how to rename things, how to refactor our code using the little quick action. Remember the little light bulb that we could make changes to by hitting “Control” and “Period” on our keyboard, and then using our arrow keys to make selections and to rename all uses of our variable name throughout our entire code base. We probably talked about a lot more than that as well, but that’s going to wrap it up here and we’ll start again in the next lesson. We’ll see you there. Thanks. Hi, I’m Bob Tabor with Developer University. For more my training videos for beginners, please visit me at devu.com. In this lesson, things are going to get a little bit more interesting. Based on user input, we’re going to write logic to execute either one block of code or another block of code. When I use the term logic, I mean that we’re going to make a decision and execute some code based on some condition that could be the user’s input from the keyboard, maybe the state of the computer system itself, maybe some of the data that we have access to are available to us, but somehow we’re going to make a decision on whether to branch out and execute this code or execute this other code. Let’s begin the way that we normally do by creating a new project, and I’m going to go to “File”, “New”, “Project”. Make sure to choose a C-sharp Console application, and we’ll call this project decisions and click “Okay.” What I want to do is we’re going to create a little game and we’re going to do it right here in static void main. I’m going to go ahead and start typing. You can pause. Try to catch up with me. Hopefully, most of this will make sense. Let’s go ahead and run the application, and here we’re going to play Bob’s big giveaway and we can choose a door. What’s behind door one, two or three? I’m going to choose what’s behind door number one, and I said, hey, you won a new car. Awesome. Let’s play again, I’d like to win something else. Now we can type in the number two and, well, nothing really happens at all. I’m going to hit “Enter” again on a keyboard and the application just ends. We can try the same thing for three, but I suspect the same thing will happen with number two, and I can just type something randomly and again nothing really happens here. But let’s start at the basics and talk about this if statement that we’ve created here, which is really the purpose of this lesson in the first place. The if statement is called the decision statement because we will decide whether to execute any of the code inside of this inner code block based on this evaluation that we’re going to do after the if keyword. In this case, what we’re doing is evaluating whatever the user typed in and we’re gathering that from the Console.ReadLine like we learned in the previous lesson. The user typed something in then hit “Enter”. We got that now and the user value variable. We want to perform an evaluation to see if what the user typed in is equal to this literal string number one. Here’s where hopefully, I want to call your attention to this, you can see that I’m using two equal signs next to each other. We already learned previously that a single equal sign is actually an assignment operator. We’re assigning the value of whatever the user typed in, and in this case in the Console.ReadLine to the variable user value using this assignment operator. But whenever you use to equal signs next to each other, you’re going to do an evaluation for true or false. Whatever’s inside of this opening and closing parentheses, we’re going to perform an evaluation. Is user value in fact equal to the number one or rather the string character one, or is it not equal to the string character one? It can only be true or false. Based on that, if whatever the evaluation of that expression is, if it turns out to be true, then and only then will we perform the code defined in the code block immediately after that if statement. If that’s not true, if this turns out to be a false statement, then we’ll just ignore whatever is inside of this code block and we’ll continue the execution of our application to Line 23 and then beyond. That’s how it works. But I tell you what, this is a very interesting example because obviously here we have we have no prize for door two or three. Then what happens if somebody just types in four, five, six or SDF or whatever on the keyboard? We need to account for all of those scenarios in our application. Let me continue typing in some code here, and you can again pause the video if you need to to follow along. But we’ll start by using an else if statement right below our code block for the if statement, so here we go. Let’s stop right there for the moment, and you can see that in order to evaluate additional conditions, I can use the else if statements. In fact, I have two of them here. If this first evaluation is not true, then we’ll continue on and do a second and a third and maybe a fourth and fifth, how many other evaluations you want to do. However, if this is true, then will no longer run. Any of these additional checks will just continue on to line number 33, the same is true here. If this is not true, then we’re going to evaluate this next expression. If this is true and we execute the code inside of the code block immediately following it, then we’ll just go ahead and skip over this last else if statement and continue on to line number 33. If we were to run the application, let’s go ahead and just quickly run through scenario number 2. Hey, we want a boat and scenario number 3, which obviously would allow us to win a cat, but then we still haven’t accounted for the situation where we type in four or anything else, like the word or just random letters on the keyboard. Nothing really happens in those situations. What we really need is what I would call a catch all case. To do that, we’ll just create an else statement below that at the very end of our if else, if construct, and so here what we’ll do is just that string message equals, sorry, we didn’t understand, and then Console.Writeline(message). Now, we’re catching every other case possible, no matter what the user types in. Let’s go ahead and run the application. Again, I’ll just type in some junk from the keyboard. Hit “Enter” and says, sorry, we didn’t understand, and we continue on. That’s how and if decision statement work. It also has these optional parts of the else if and the else statements for either additional evaluations or what I call the catch all just in case none of the conditions are true. Now, there’s a couple of things about this, and we’re going to continue on to talk about one other type of decision operator that we can use a conditional operator. But before we do that, here’s an opportunity to clean up our code. Let’s look for areas where we’ve essentially got the same code repeated over and over and over again, and I can see a couple of of instances where this is true. The first would be where we have this Console.Writeline(message). You see, we’ve repeated that in line 20, 25, 30 and 35. Wouldn’t be great to keep our code a little smaller and only use that once at the very end of our evaluation. Like, put it right there outside of the if else, if else, decision statements. Let’s go ahead and just remove those from there completely. But when we do that, notice that I’m getting a red squiggly line under the word message. The name message doesn’t exist in the current context. We’re going to talk about scope and declaring variables inside of certain scopes and a little bit, but just to lead up to that conversation. Essentially, when we defined a variable inside of an inner scope, it’s not available outside of that scope. In other words, if we define a variable inside of a code block, inside of the curly braces, it’s only available inside of those curly braces not available outside of those curly braces. What we’ll have to do is define that message variable outside of our if statements so that it’s accessible to all of the inner code blocks, as well as our Console.Writeline(message) here in line number 35. It’s a very simple fix. We’ll just do this. String message equals and then we’ll just set it to an empty string to begin with. Now, you’ll see a different message, a red squiggly line. But we’ve seen this before. You can’t define the same variable twice, even if it’s in an inner scope. What we’ll do is just say, instead of defining the variable message there, we’ll just set our existing string variable called message to the value like so. Great. Now, our applications should run, we’ve eliminated a lot of code, and admittedly, I created a straw man here. I wrote more code than I needed to, but I wanted to illustrate this point. Again, if we were to run the application. It works correctly. But there’s one other change that we can make. Code blocks as we’re using them inside of, if else, if and else statements. If there’s not more than one line of code to execute, then we don’t even need to use the curly braces. In other words, since there’s just one line of code here underneath my if statement, I can just remove it and make it small like that real compact. Same is true here, and same is true here. Now, in this case, maybe just to illustrate why you would need the opening closing curly braces if I were to do this message equals the message plus, you lose like so, and I’ll even add a little space here to make it look correct. Let’s go ahead and test that else case just real quick, and I’ll type anything in there and hit “Enter” and says, sorry, we didn’t understand you lose. Notice that we were able to concatenate two strings together. I did it on two separate lines you don’t really need to. But if I were to attempt to remove the opening and closing curly braces there, we’re going to get a very different result when we run our applications. For example, if I hit “3”, notice that you want a new cut, you lose weight. Why did that happen? You want a new cut, but you lose. Well, there is no such thing as a free cut, but anyway, it’s because what it’s really seeing is this like that. If we want these two to be evaluated together inside the same code block, we have to include them in the same code block. Otherwise, this being outside of that code block will execute no matter which of these, if or else if conditions are true. Let’s go ahead and put that back in there to illustrate that idea. In fact, if we were to do something like this, I can even make this a little bit smaller. Let’s comment that out, and I’m going to show you a new operator, which is just this. Now, instead of going message equals message plus you lose, essentially, I’m saying, give me whatever’s in the variable message, concatenate on the word you lose, and then assign that into the variable message. That’s what I did here. I just do it all in one step right there, where I say, whatever’s in the variable message on the end of that concatenate, you lose. This is the assignment and concatenation operator combined into one. Just a little shortcut there. Now let’s do this. Let’s talk about another style of decision statements. It’s actually an operator called the conditional operator. This works well if you have an if or else scenario and you don’t have multiple items to evaluate like we did here. I’m going to copy some code from lines 14-15 and line 16 too, I’ll just copy all of those, and we’re going to paste them down below our command area. Then what I’m going to do is this. Will do this a little bit different this time. There we go. Now I’ve written a lot of extra code that I need to, I’m going to show you how to shorten this up in just a moment. Here, the key to this is this little evaluation that I’m doing on line number 42. Remember that we’re going to evaluate anything in between the parentheses. Whenever we see the double equal sign, that means we’re doing an evaluation. Is the user value that they typed in and submitted through the previous line of code, line number 40, is that equal to the literal value 1? If this equates to true, then what we want to do is, everything after the question mark, we’re going to take that value and assign it to our new variable called message. If the user types in one, will find the literal string boat and will assign it to the variable message. However, if this equates to false, so they type in something different, then anything after the colon will be taken and assigned to the variable message, and we’ll use that below. Let’s go ahead and run the application, we’ll run it twice. We can choose the door and if they choose door number 1, they win a boat. However, if we run the application a second time and we choose anything else, then you’ll only win a strand of lint. Again, this is only useful in a if, else condition, not when you have multiple conditions to evaluate. Now, let’s address this last little part here because I can shorten this up considerably. Notice, in order to get it all to print out on one line, I only use Console.Write, then I typed out the literal string, and then I have a second line where I’m actually then printing out the actual message from line 42. Then finally, to add a period at the end, I’m having to do yet another Console.Write statement in order to add a period. I can shorten all that up in one line of code. Watch how I do this. In fact, let’s go ahead. I’ll comment out these lines individually, like so. Then I’m going to use a replacement character inside of the Console.Write line in order to shorten this up a little bit. We’ll use the WriteLine instead, and we’ll fill you one a and then I’m going to use what I call a replacement code of zero. Then after I give it that literal string and you use a comma and then give it the actual message variable that I want. Whatever’s inside of this, I want it replaced in here. Eliminate the curly braces with the zero and put the message variable value inside of there. Let’s run the application again just to see this working. I’m gong to type number 1 and get the same result. Now, what if we wanted to expand on this idea here? Let me comment that out. What if I wanted to replace two values inside of that Console.WriteLine string? Let’s do something like this. You entered and then we’ll go 0. Therefore, you won a. In this case, after the comma, I’m going to enter the user value and then the message goes, make sure you can see that. Hopefully, you can see that on screen at one time. I need to do one little thing here, is change that to a 1. This says, take the first item. In software development, typically you don’t start with the number 1, you start with the number 0. I don’t know. We’re going to see this pop up again and again. The first item in the list will be at element 0. The second item in the list will always be at element 1 and so on. The very first item, this will be matched and replaced by the very first item in that comment a limited list of input parameters, after the literal string that little template that we’ve created for ourselves. Then here we’re going to do a second replacement and replace that with whatever is inside of the message variable, when we run the application. We type in number 1. It said you entered 1; therefore, you won a boat. Awesome. That’s enough for one lesson. Hopefully, you’ve learned a couple of important things in this lesson. First of all, we talked about the if decision statement, as well as the else-if and the else, and how to do a comparison and evaluation between two values to determine true or false. If we’re using an if statement and we’re doing that evaluation, then the code that is in the code block below it will get executed if that evaluation is true. If it’s not, it’ll either drop down to a second subsequent evaluation or even do a catch-all in the else statement. We talked about using curly braces for a code block versus when you don’t need them. We talked about keeping your code nice and tidy and small. We talked about declaring variables inside of scope and inner scope and outer scope as defined by our curly braces for code blocks. We talked about the conditional operators, being able to all in one line do a check for true or false, and if it’s true, assign one value versus a different value to a new variable. We talked about format codes inside of literal strings for our Console.Writeline and how to replace those replacement codes with variable values that we then also pass in our Console.Writeline statement like you see here at the very bottom in line number 49. Again, we covered a lot of ground. Hopefully, this all makes sense, if not, rewatch the video, just watch those portions that didn’t make sense. Make sure you’re typing in the code yourself so that you can come to some of these epiphanies as you’re typing. We’ll pick it up in the next lesson. See you there. Thanks. Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. In this lesson, I want to spend a bit more time talking about some smaller syntax elements of the C# language that you need to master to understand how a properly form line of code is constructed in C#. In one of the previous lessons, almost like the first lesson, I said something to the effect that just like you use a period or question mark or exclamation mark at the end of a sentence in English to complete a thought, you also use a semicolon at the end of a line of code and C# to denote a complete thought. To extend that analogy a little bit, I may have briefly referred to C# syntax as having nouns and verbs. So I want to elaborate on these things and clarify what I mean by that in this lesson. I’m going to talk about the basic building blocks, and I guess you could say, parsing the parts of speech in C#. Let’s start off at the beginning. Statements are what you call complete thoughts in C#. Typically, one line of code. A statement is made up of one or more expressions and expressions are made up of one or more operators and operands, so we’ve seen a number of statements and expressions and operators and operands already, whether you realized it or not. As we’re taking a look at some of the previous work that we’ve got here, I’ve got the variables project from a previous lesson opened up. For example, you can see that essentially each line of code is a statement. Each of them are made up of one or more expressions. Here, for example, is an example expression. This happens to be a variable declaration statement made up of a operator, which in this case is a keyword Int for the data type integer, and then an operand, in this case, a variable name. We also use another operator, the semicolon for the end of the line of code. Another example would be here where we have an assignment where we’re actually calling a method. Here is an operand. It is the name of a class, and we’re using the open-close parentheses. Remember, these are operators. This is the method invocation operator. Then we’re using another operator here, the assignment operator, to assign the value of this expression to another operand, the name of the variable that we created. We were to look through the code, we could continue to parse out and understand what makes up operands, operators, expressions, and then entire code statements. Now, operands are similar to nouns. They are things like objects and classes and variables and even literal values. These are the subject, I guess you could say, of your statement of code. They’re pretty easy to remember because typically you give them names, you define the values yourself, and so on. Now operators are similar to verbs. They are things like the addition operator or the string concatenation operator. These are things that act on the operands in order to perform some action. Typically, you’re going to use the built-in operators, although you could create your own operators. A little bit of an advanced topic, but there are actually quite a few built-in operators and you’re going to need to memorize many of them. That’s how you come to express yourself in C#. Fortunately, as you start out, you probably only need to know a handful to be productive. What I want to do in this lesson is to focus on a few that I think you’re going to use probably 90 percent of the time as you begin learning and you can obviously add to that list as we continue. I’m going to actually present these in a rapid-fire fashion. I created a very nonsensical application. You can open this up, download it from wherever you’re currently watching this video or wherever you originally downloaded it from. I called this project OperatorsExpressionStatements, and the application itself does absolutely nothing meaningful at all. All it really does is show you some examples of the various operators and expressions that you’ll come across whenever you’re working in C#. At the very outset here you can see that I have a variable declaration. We talked about this already. I did something a little bit different this time where I’ve declared several variables all upfront as integer. So x, y, a, and b are all defined as integers. Just wanted to show you something a little bit different there. By separating them with commas, it’s an easy way to declare several variables of the same type, all on one line of code. I typically don’t recommend this, but you might see this around in use in books and on the Internet. Next up, assignment operator. We’ve already seen the equal sign at work in that capacity. Note here in line number 22 and following that there are actually many different mathematical operators. We’re only looking at the most basic ones, but there are also some advanced ones as well. But here we have addition, subtraction, multiplication, and division. As I demonstrate here, you can use parentheses to actually change the order of operations. In this particular situation, the parenthesis is not a method invocation operator. It’s actually how you would typically use it in an algebraic or mathematical sense. You would use it in order to specify the order of operations. So perform this expression first, then this expression, and then take the result of those two and multiply them together in that third expression and then assign them to the value of x. Then there are operators that are used to evaluate. We’ve already talked about the equality operator, where we’re using two equal sign next to each other to make sure that these two items are in fact equal. Here, again, we’re using parentheses in yet a different capacity to define the boundaries of our expression that will either equate to true or false. X equals Y is either true or false. We can use greater than we can use the less than operator. We can use greater than or equal to less than or equal to. All of these, again, should produce a true or false result. There are also two conditional operators that can be used to expand or enhance an evaluation, and they can be combined together multiple times, as I say here in the comments, so I could ensure that both X is greater than Y is true and A is greater than B is true by using the logical and operator. There’s also an or operator to say either X has to be greater than Y or A has to be greater than B in order for this outermost expression to be true. So here is the logical or two pipe characters next to each other. Then I guess we’ve already talked about that in-line conditional operator where we have some item that’s being evaluated. Then if it’s true, then we’ll take the first value and if it’s false, then we’ll take the second value. In this case, we’re assigning either car or boat into this message variables value. Then also wanted to talk about member access and method and vocation. We’re going to talk about object oriented programming quite a bit later on in this series of lessons, but we’ve already said how the console was a class and classes are containers, for lack of a more robust definition, for methods. The way that you access a member method of a class or an object is by using the dot or the period that is the member access or operator. Furthermore, we talked about the method and vocation operator. Here we are, invoking a method called WrightLine by using the opening and closing parentheses. In this particular case, we’re passing in an input parameter. Again, we want to hold off and talk about input parameters and methods a little bit later. But as you can see, here’s a number of different operators, and these are just what I would call a very baseline set. You need to memorize these so that you can express the most basic of C# commands and understand exactly what it is that you’re trying to do. It’s not an exhaustive list by any stretch of the imagination, but you will probably need these about 90, 95 percent of the time. Then you can expand your vocabulary of other operators and keywords over time. In each of these cases that we just looked at, an expression is made up of a combination of operands, which are things like the literal strings and variables and objects like the console class itself, and operators. Things like the addition operator, or shrink incantation operator, or equality assignment operators and so on. You use expressions then to form complete thoughts, statements in C#. Which are how the actions or the instructions of an application are expressed to the compiler and ultimately to the.Net runtime, which executes your application. Why am I telling you-all of this? Why go through this little English lesson, passing out the different parts of speech if you’ve ever had to take an English class? Well, it will help you to understand why this is not a valid statement in C#. You can’t just type x plus y and then give it a end of line character and expect it to do anything. The C# compiler will look at that and say, what are you trying to accomplish here? Have you lost your mind? What do you want me to do with all this? Fortunately, in situations like these, as you can see, Visual Studio can catch these syntactical mistakes even before you attempt to run the application. If we were to hover our mouse cursor over the visual guidance here, the red squiggly line, you can see that the fundamental problem with this line of code is that only assignment, call, increment decrement, and new object expressions can be used as a statement. What’s the problem here? Well, this is not a properly formed statement. We’re not assigning, calling, incrementing, decrementing, or creating new object expressions. What? We’re not formulating a complete thought, a good sentence. I could create an English sentence like this, the red ball. You would say the red ball does what? Who has the red ball? You can understand that just because you use words doesn’t mean you’re creating a complete thought or expression inside of the English language. Same thing is true with C#. That’s all I’m trying to say here. For beginners, understand that there’s a proper syntax, just like there’s a proper grammar in the English language. Understanding this is really a big step towards solving your own problems whenever you’re phrasing C# instructions that the C# compiler will understand and accept and ultimately compile into code that will be run by the.NET framework. Here, let’s recap what we talked about in this lesson. First of all, statements are complete instructions in C#. They consist of expressions and a statement is like a sentence in the English language. Expressions are composed of things like nouns and verbs, in other words, operators and operands. The operands are things like nouns, they’re the subject or what we want to do something with. Then there are the operators, which are more like the verbs. These will act on the nouns to perform some action. We said that operands are like variables and classes, literal strings. These are things that we get to name ourselves. They give the meaning to our application where as operators are, for the most part, built into the language and we have to memorize them. To start off, you might use something like what I’ve given you here in the form of a project for a cheat sheet. But I think you might just be able to walk your way through and rationalize your way through. Now that you understand that there’s a proper way to format a line of code, you might say, okay, what do I need to do here? You might be able to reason your way through the operands and the operators. I’m going to need a variable to contain some values. Once I have created that variable in memory, now I’m going to need to assign it to something now. How am I going to get to that something? I’m going to need to take another variable and this literal value, and I’m going to need to add them together with an operator. Hopefully you get the idea there. I hope that this was a useful exercise. I think it’s useful for beginners to understand that there are syntax rules, and they’re not so unlike what you’re already familiar with. Maybe they look a little bit different than your typical English sentence, but they still have to make sense and they have to perform an action or to do something. When you see errors, sometimes it’s because you typed something incorrectly. Then sometimes is, you may not be using the right forms of speech in a sense in order to express that complete thought at C#. Let’s pick it up in the next lesson, will see you there. Thanks. Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. In this lesson, we’re going to focus on iteration statements; a specific iteration statement called the forlteration statement. Sometimes you’re going to need to loop or iterate through a sequence of things to find something that you’re looking for, to find a successful match. Actually, you’re going to do this data manipulation more than you realize. You’ll have to trust me that this is a very important tool in your toolbox that you’re building. As you can see, I’ve already taken the liberty of creating our project. I called it forlteration, pause the video, go through the steps that you already know how to perform to create a new console window project, and catch up with me. I’m going to begin to add some code here on line 13 in just a moment. Now, the syntax that we’re going to write here in just a moment is possibly the most cryptic of anything that you’ve seen yet. I’m going to be completely honest, sometimes I get things a little bit mixed up myself, but don’t worry. After we struggle through it once or twice, I’m going to share the little secret that I used to get it perfect the first time, every time. Having warned you about the complexity of the syntax, I’m still betting that you could figure it out and read it even before we actually attempt to run the application, even before I take the time to explain what each little bit of the application is doing. Let me write it out here and then we’ll try that. Very simple, at least very compact section of code here. Actually, you need one more line of code, Console.ReadLine. There we go. Now, ready for action. What do you think that this code does? Got a theory in mind? Well, let’s go ahead and run the application and see if your theory is true. You can see that we have a list of numbers from 0-9 and then we can hit ”Enter” to continue on. We’re using C-sharp to execute this little block of code right here until a certain condition is true, at which point we will stop executing that line of code and continue on to line number 17. This for statement says that we should begin by declaring a variable. We’re going to call it i. We could call it anything we want to, and we’re going to initialize its value to zero. Now, as long as i is less than 10, we’re going to continue to execute the code below it in our code block, defined by our curly braces. Each time that we iterate through, we’ll increment the value of i by one. This little bit right here is probably the part that you probably wouldn’t completely understand unless I explained it. You remember how we use the plus equals sign in order to automatically take the value of message and add something to the end of it and then assign it back to the value of message? Remember that a couple of lessons ago? We’re essentially doing that here. This is the the increment operator, so we’re going to increment the value of i by one. Again, we’re going to declare a variable and initialize the value. Then as long as this middle part is true, we’ll execute the code below. Once we finish executing, then we will increment the value of i and then do that evaluation one more time. If it’s still true, then we’ll execute this code again. We’ll increment i. If this is still true, we’ll increment it again and so on.. That’s how it works. Yes, this is cryptic syntax, but if you can just separate the three parts in your mind by remembering that there semicolons that separate them, that can help. You know you’re going to need to start off with some counter of some sort. You’re going to need a condition and then you’re going to need an incremental at the end. Again, I’ll show you a way to remember this so you never forget it. But before we do that, let me comment out this line of code and give you a variation on this idea. This would be fun. Here we go. You can see that I simply added inside of our code block for the for iteration statement, another if statement with its own code block inside of it. Here, we’re checking the current value of i, and once we find something we’re looking for where i is equal to 7, then what? We’ll perform this code. What is this code do? Well, this part’s obvious, but this break statement may not be so obvious. You use the break to bust out of or break out of the forlterations. We’re going to make it to the value where i is seven, and then we’re going to hit the break statement and then we’ll continue on to line number 23. Let’s see it in action. It’s not going to look all that exciting, but I got an idea. It found seven and it pretty much finished. I have an idea. Why don’t we watch this execute line by line? To do that, we’ll use the debugging tools inside of Visual Studio, which we have not even talked about up to this point, and yet is probably one of the most important features of using Visual Studio as opposed to just using a text editor and a command line compiler. To make this work, what I’m going to do is actually set a breakpoint here on this line of code. Now, how did I do that? I just went to this left most column and I clicked in that gray column and it created a little red dot and off to the right hand side. You see that that whole line of code is outlined in red. There are, truth be told, a number of different ways to set a break point. Probably the easiest way to do it is is what I just showed you. But there’s also keyboard shortcuts and there’s menu options as well. For example, with my blinking cursor online number 16, I’ll go to the debug window and I’ll select ”Toggle Breakpoint’. ‘ If we look over to the right hand side, you can also see that the F9 key will accomplish the same thing. Great. Now, let’s go ahead and run the application and see what happens. Immediately the application pops up before anything can be printed out to the console Window, notice that we have paused the execution of our code and we’re paused right here on this breakpoint. Now, at this point, I can do a lot of cool things. First of all, I can see what my local variables values are currently. I can also change the value of those variables. I can monitor those values. I can change which line of code will get executed next and a bunch of other things. Now, this is not a series on debugging. I could easily spend an hour showing you a lot of cool little features. However, what I do want to do is call your attention to this little window at the bottom. Currently, right now we’re in what’s called debug time, and with the application execution pause on this line of code, the next line of code that’s going to execute is that line right there that’s highlighted in yellow. I can look at these little windows like this locals window, for example, and you can see that the locals Window will contain any variables that are currently in scope at the moment. Obviously, args is something that we haven’t talked about yet. Let’s ignore that one. But what I want to focus on is the value of i. Current value is zero. How do I know that? Because I’m looking here in the value column. I can also see what the data type of I is. It’s an integer. I were to hover my mouse cursor over I you can see I’d be able to see it there as well. If I were to go and pin down that value, I’d be able to monitor it as well in this little helper window. In fact, I can drag it around here. Now watch what happens. Let me readjust some things here. I’m going to step through this line of code. Now, there’s a couple of different ways I can step through the code. I’m going to recommend that we only talk about step over for right now. When we learn about methods we can step into and step out of but for right now this middle button right here, the step over or the F10 key on your keyboard is what we want. I’m going to click it once and notice that we jumped from line number 16 to line number 22. Why was that? Well, the reason was because I was not equal to seven, so we didn’t execute the code inside of the code blocks underneath the if statement and we jumped to the end of the ‘for’ code block. Now let’s continue just to step through this. You’re going to see that we’ll increment I by one. Now when we do that, notice what happen. The value of I change from zero to one, and that change is indicated by a change in color. Whenever you see the color red that means something changed in the previous line execution. The value of that variable changed from some of the value now to the value of one. We can also see this in this little mini window right here as well. How it is now turned to the color red. Now that we’ve incremented, we’re going to do the next check to see is I still less than 10. Here we’re going to step one more time into our program. Here we’re going to step and in the Line 14 which opens up our code block and we’ll do another assessment is I currently the value of one equal to seven? No. So we’ll jump out of that if block and continue on, and we can just continue through this exercise until we reach where I is equal to seven. Now, truth be told, I don’t have to keep hitting the step over button. I can just use this continue button and this will just keep bringing me right back to the break point. This basically says, continue running until you hit another break point. Here at this point now I see that my I is equal to seven, and that’s what I’m checking for. Things should get interesting right now. I’m going to go back to start stepping line by line through my code. Here’s where I hit the console that right line and if I look now on screen it actually did write that to the console window. Now I’m going to step to the next line of code and notice that it jumped out from the brake statement outside to line number 23 outside the ‘for’ statement to the console that read line we can hit continue from that point on. Our application is still running until we hit the enter key on the keyboard and then we’ve exited out. Very cool. Now, you may have found it laborious to step through a number of times or even hit the continue button a number of times until we found just the right conditions. What we can do is make this break point into a conditional break point. To do that, I’m going to hover over the little red stop sign I guess you could call it in the left most column and I’m going to click this settings. Here this will open up a little break point settings window right in line in my code, it pushed all the other code down. Notice that it goes from Line 16 here to Line 17 way below it. I’m going to add a condition. Whenever a conditional expression is true, then we’ll break at that point. In our case, when I is in fact equal to seven, then we’ll break on that break point. You can see that when I hit “Enter” on my keyboard, it’s saved, and now I can close this. You can see that the little icon changed from just a red stop sign to having a white plus symbol inside of it. Now when we run the application notice that I is seven and that I is seven in our little window here before we even stopped into our break point. Now we can continue stepping line by line through our code and continue on. We got our result, and we can continue on. Again, I could spend an entire hour just showing you other cool little features that will help you debug your applications but understanding how to set a break point, how to run your application to a break point, how to step through line by line and then how to resume, at least resume temporarily or continue by using the continue button. Those are the key concepts in debugging. In using the Visual Studio debugger. Now let’s go ahead and it’ll turn off this break point. From now on what I want to do is just eliminate it I can do that one of two ways. To completely turn it off, I can just click and it’ll go away. Or I can temporarily disable it by using this little icon that was next to the gear that we clicked earlier. Now, you can see there’s a little outline in the left most column and an outline around the line of code that had the break point, but no longer are we actually going to break on that line. Let’s do this. Underneath the ‘for’ statement from before but above the console that read line, I want to do what I promised to at the very outset which will show you a way a foolproof way that you can get the syntax right for a for iteration statement, and truth be told for just about anything else by using a little secret code snippets. It’s not that much of a secret but you probably didn’t know about it, did you? To do this it’s real easy. If you can remember I need a for iteration statement just type in the word for. You’ll see that it pops up in the IntelliSense. If you look after the IntelliSense pops up a little message to the right there, code snippet for ‘for’ loop. Note: Tab twice to insert the ‘for’ snippet. Let’s do it. Tab, tab, and there we go. Notice that it went ahead and pretty much set it all up although there are some parts that we’re going to have to change like, for example, the length. I don’t have to use the value I for my iteration statement as my placeholder, as my counter, whatever you want to call it. I could call something like my value and notice as I’m typing, and then I hit the tab here on my keyboard, it changed everywhere that was using the I variable label to my value. Very cool. Hitting tab also took us to the next spot in our code that we’re going to need to replace, which was the length. Or in other words, how many times should this ‘for’ loop iterate? I’m going to say we’ll do it until my value is less than 12. Now, here again, we can use a number of different equality or inequality operators so we don’t have to use the less than we could use the equal or we could use the greater than whatever makes sense for our application. But I want to keep simple and leave it just like that. Once I’m done making changes I can see the “Enter” on my keyboard. There were some highlighted areas that were highlighted in gold color that indicate that these are replacement areas that go away. Now my mouse cursor is right between the opening and closing curly braces and at this point then I can continue to create my application, write line, and then my value like so and then we can run our application and we would get the following results. Just to recap. It was a short lesson but we learned a lot. Not only did we talk about for iteration statements and why you might want them and we’ll see them at use later, but we also talked about the debugging tools just briefly, and how to step through a code, how to monitor the value of variables, how to use the break statement to bust out, to break out of a iteration statement. We looked at code snippets and how to replace values in a code snippet in order to make it our own. We’ll use some of these techniques that we learned here throughout the rest of the series, very important video. Let’s continue on the next lesson. We’ll see you there. Thanks. Hi, I’m Bob Tabor with Developer University. For more my training videos for beginners, please visit me at devu.com. In this lesson, we’re going to talk about arrays, and I’m going to start by making a case for why you need arrays in the first place. Often you’re going to need to work with several related variable values. But how do you work with multiple variables and treat them all as if they’re part of the same group? Well, let me show you how not to do it. You can see an example of that on screen. First of all, I’ve taken the liberty of creating a project called understanding arrays, so make sure you catch up with me. Create a new console window application and you can just follow along. You don’t need to type this part in. It’s wrong anyway. You can see what I’ve done here. I need to keep track of five numbers, and I need these numbers to be related to each other, so without any better tools in my toolbox, I might just create something called Number 1, Number 2, Number 3, Number 4, and give them each a value. Now I want to find which variable holds the value of 16. I love to be able to loop through them like we learned about previously, to find which of the values hold Number 16, but I can’t really do that. I’m forced to create an if else structure. As you can see here below, in order to ultimately find which variable has the value of 16 inside of it. This is not the right way to go about working with multiple values that are somehow related and you want to treat them as a group. There’s a better way and that, as you might assume, would be with arrays, so we comment all of this out. Previously I talked about a variable as being a bucket in the computer’s memory that will hold some value. But let’s expand our thinking about this for just a moment and talk about an array. Think of an array as like a bucket, or maybe even better, a tackle box. Ever seen one of those? If you go fishing, there’s a lot of little compartments inside of it, and each one of those little compartments can hold something. Usually a little worm or whatever the case might be. What if we were to use that instead of a bucket? What if we were to put values in each of those little tray areas inside of the tackle box and store that up in memory? Then whenever we needed a value out of that tackle box, we just need to take it and look through and find the particular compartment with what we’re looking for, in order to work with it. That’s the idea of an array, at least if you want to overextend the bucket analogy. Another way to think of an array, it’s a sequence of data, a collection of data, although I’m hesitant to use those specific terms, because they have very specific meanings in.NET. Think of it in a very general sense. You have a collection of data you want to keep together, how do you do it? Well, one of the ways you can do that is with an array. Let’s do this and I’m going to go ahead and create my first array here. I want you to follow along and notice that I’m using square brackets, I’m not using curly braces when I’m working here. First of all, let’s take a look at the declaration of our array called numbers. It is an array of integers. In other words, there are going to be multiple integers all collected under this same umbrella named numbers. You can see that not only am I creating the declaration for this array, I’m also using an equal new in five. Some of this, like the equal in the new part, we’re going to talk about what that really means a little bit later. But for now, just accept it as how you go about creating an array. Then notice next to that, I have int and then inside the square brackets, I have the Number 5. So that’s how many elements that I want inside of my new array. I want a new array of integers that can hold five integers inside of them. Next what I do is I begin to access each element of the array and put a value inside of that element of the array. Here’s the 1st element of the array, the 2nd element of the array. Remember we’re zero based? Here’s the 4th element of the array and the 5th element of the array. Five elements inside of the array, just like we defined here in line Number 31. Now what if we wanted to access the value inside of one of the elements of the array? Well, I would do something like this. It’s a Console.WriteLine, obviously. Now what if I wanted to get to and print out the value that’s in the 2nd element of the array? Well, then I would use the correct index of the array to access that element. Here’s the numbers, and I want the 2nd element, which means I’m going to use the Index 1. So I’m going index into that array to get to the correct element. In this case, the 2nd element is at index Number 1. I can print that off the screen and we do a read line here. Like so and we can quickly run the application. You can see that we are printing to screen the Number 8, which in fact is the 2nd element of our array. Now the other thing that we can do is actually determine how many items are in the array by looking at the length property of the array itself. Console.WriteLine, and I’ll just go numbers.Length. Let’s see what that will output. In fact, let me go ahead and comment that out and run the application. You can see that we’re able to programmatically determine how many items are in the array by using the length property of the array. There’s five elements inside the array. Great. Now what would happen if we were to attempt to insert data into another item, a 6th element of the array? What do you suppose would happen here? Well, we’ll try it. We’ll run the application and you’ll see that we get an exception and IndexOutOfRangeException was unhandled. In other words, we are outside of the boundary of the space that we defined inside of our array. We’re trying to access compartments that were never created in the computer’s memory inside of our little tackle box. In order to remedy this, we can either redefine our array at the time of declaration that we need actually six items or we can go ahead and we can change at runtime, the number of items in our array. That’s a little bit of an advanced topic. I don’t want to talk about how you would go about doing that, but it is possible to do it programmatically at runtime. Let’s move on from there, and let’s talk about maybe a simpler approach to creating new arrays, and that is to not only declare the array, but then also initialize its values at the time of declaration. So let me comment out everything I have here and we’ll do this. Now, instead of giving it a specific size, we’re going to let the compiler figure it out on its own. Because we’re just going to start typing in the values of the elements that should be stored inside of our array. Now in this case, I can create it or just put all the items I want to put in there, and I can trust that the new array that will be created in memory will be able to hold all six items this time. Let me comment that out. We’ve been working specifically with integers, but what if we were to work with strings? How would we go about doing that? Well, same idea here. In this case, we want to give it a number of literal strings. Like so, and so let me move this over a little bit. You can see that we are able to create an array of strings. We don’t have to declare upfront how many elements we want in our new array, we’ll let the compiler figure that out. It will create four items. Now there’s a number of different ways that we can loop through to access each of the items in our array. Let me show you two ways, and one of them is going to be what you’re already familiar with the for loop, right? I’m going to go for tap ”Tab”, and so we’ll start with an integer I equals zero, and now let’s do this instead of names dot Length. Right? Then inside of here we’ll go and do this

    Console.WriteLine and we’ll go names. What do you suppose we’ll put in the middle here? We’ll use the value I. So what we’re going to do is start at zero and continue iterating through until we reach the length of our array and then we’ll stop and jump out of our array. But until then, we’ll do a Console.ReadLine here, and you can see that this will allow us to print out all four items inside of our array to the Console window. Great. Now there’s a lot of management of this, I hear, but there’s an easier way to go about this. Let me comment this out real quick. I’m going to show you a second style of iteration statement. In this case, we’ll just do this. We’ll do foreach and I’ll go ahead and use the code Snippet. I’ll just go tap ”Tab”. For each string name and names I made up the term Name as singular in Names is actually what we called our array right. So now I’m going to hit ”Enter” on my keyboard twice and I’ll just do Console.WriteLine name and let’s go to Console.ReadLine. What this will do is it’ll allow us to essentially loop through every single name in our array of names and for each item, it will copy the current element into this temporary variable code name of type string. Then we can use that to do whatever we want. In this case, we’re just going to print it off the screen so much easier, that is, but we can use either technique in order to iterate through our sequence of data. All right, now, let me show you one last thing you can do, it will be pretty powerful stuff and we can create arrays of different things. What if we wanted to take a string and reverse the string? How would we go about taking, for example, the name Bob Tabor and reversing that to Robert Bob? How would I change that? Well, what we can do is take a string and convert it into an array of individual characters. Once we have an array of individual characters, we can then say, go ahead and reverse the order of those items so that the last becomes first. In the first becomes last, so let’s do this, I’m going to I’m going to create a string called Zig, and it’s going to contain one of my favorite speakers quotes that I have a patterned my life after ”You can get what you want out of life if you help enough other people get what they want.” Now that’s a very long line of code. What I would probably do is I would try to chop this up into multiple lines of code. We said this before that you can do something like this in C-sharp. All I’m doing is going to just break it in half and use this concatenation operator to marry the first string and the second string together, so that’s all really one line of code. Now that I have this, what I want to do is create an array of characters. I’m going to use the Char Keyword, which is the data type Char, meaning I want one character, but I’m going to create an array of characters called charArray, and then I take this zig string and I’m going to call a helper method on it called ToCharArray. Every data type has some helper methods that are built into it by the dot NET Framework. What this will simply do is take a long string and we’ll split it up into individual characters and put those into an array of characters. Now that we have our statement here in an array of individual characters, I can do something like this. I’ll call Array.Reverse and I’m going to pass in the character array. Then finally, what I want to do is we’ll do a foreach tab tab for each char, and I’ll just call this a ziglarchar in my charArray. Console.Write, not WriteLine, but just write, and the zigChar, hopefully all this makes sense. Let’s do a Console.ReadLine. This is just to show you some of the flexibility of working with arrays. Let’s run the application and now we were able to write that whole string backwards. That’s pretty much it. There’s a lot more that you can do with arrays, however, and as we move through C-sharp, you’re going to find that your use several arrays will diminish over time and you’ll start using something a little bit more elegant. Think of it as an array on steroids, or maybe like Super Array. It’s going to be called a collection. There’s a bunch of different types of collections, and we’ll learn about those near the very end of the series of lessons. But at anyway, that’s how you work with arrays. Remember that you have to declare an array by giving it at the time of declaration its size. Then you can access individual elements of array by using indexes into the array to access or to set the values in a given element of an array. We can loop through elements of an array using a four or a foreach iteration statement, and we can even use some cool utility methods like Array.Reverse to swap all of the items in the array, or there’s also ways to sort items and so on. Let’s continue on the next lesson. We’re doing great. See you there. Hi, I’m Bob Tabor with Developer University. For more my training videos for beginners, please visit me at devu.com. In this lesson, I want to show how to create and how to then call simple methods. Now, creating methods are going to help us with a number of different things as we write more interesting applications. Methods are going to help us organize our code better. They’re going to eliminate duplicate code and the need to copy something we did earlier and paste it later in our code base. They’re going to allow us then to take a certain feature or functionality in our application and give it a name and then call it by its name anywhere in our application. Then if we were to ever need to update or fix an issue with our method, with that code that’s encapsulated in a method we have to do one place instead of changing it everywhere, we copied and pasted our code. Remember what we said at the very outset of this course that a method is merely a block of code as defined by curly braces, and it has a name, and since it has a name, we can call it by its name in order to invoke that code defined in its code block. Methods are actually one of the most important building blocks that we’re going to learn in this course, and it will allow us to build more interesting and complex applications. This is definitely something that we need to understand thoroughly. To begin, you’ll notice that I’ve already created a project called Simple Method. Please take a moment, create a new console window project and catch up with me. What I’m going to do is build the most simple example. I can possibly imagine a simple ”Hello world” application again, but this time using a method. We’re going to define our helper method inside of our class program, because remember, we’re going to keep methods inside of the context of a class. Related methods go together in the same class, we’ll expand on that later. But it should be outside of the definition of our previous method, the static void main. I’m going to go right to the end of the closing curly braces for static void main, and I’m going to hit ”Enter” a couple of times on my keyboard that should put my mouse cursor after static void main’s definition, but before the end of our class programs closing curly brace, so somewhere in this area is where we want to work. We have to define things in the right place, just like we learned before, and here, let’s create our first very simple helper method. That’s all it takes. Now I’ll explain the word private when we talk about accessibility modifiers and classes. We’ll talk about the word static much later in this course. However, just to let you know, it has more to do with building console window applications than typically what you might find yourself using in a different style of application. But we’ll talk about it later. The void is something that’s important. We’ll talk about that in just a few moments here. I’m going to create a block of code and then I’m going to give it a name. In this case, the name is simple HelloWorld. Additionally, I’m going to give it an opening and closing parentheses and we’ll look at what those are used for here in just a moment. However, then in the body, I’m simply going to just write any of the code that I need, my HelloWorld function to do. Now, in this case, one line of code very simple but hopefully you get the idea. Now how do I call that method? How do I execute it from my static void main? Well, remember it has a name and we can call it by its name in order to invoke it. But remember, there’s one other piece of information that we need to provide here. Not only do we need to give it the name of the method that we want to invoke but also we need to use the method invocation operators which are the opening and closing parentheses in this context. Now we’ve called our method and we expect output in the console window. Now I’m going to go ahead and add one more line of code just so we can see our result like we always do and now when we run our application, we will get the unexciting results, Hello world. But the most important part of this was to create the simplest example we possibly could. Now that you see how easy it is to create a method and how easy it is to call the method, let’s go ahead and shut down that project. Instead, what I want you to do is open up the project and you should be able to find this where you’re currently watching this video, wherever you originally downloaded from, there should be source code available. You should be able to find that source code in before folder for Lesson 10, copy that HelperMethods project folder into your project’s directory or somewhere on your hard drive, and then you can open it up from there. I’ve already got this opened up here and you can see that I’ve created a simple name game application. Again, this is simple but at least there’s more code that we can use to demonstrate how useful methods can be for us. It’s going to ask us for our name and then where we were born and then we’re going to use the little algorithm I guess you could call from the previous lesson where we learn how to take a string, how to convert it into an array of characters, how to reverse the order of each of the characters in the array and then display it back out to the console window. That’s what we have here in our results, Oak Park Tabor Bob spelled backwards. Now, in order to accomplish this, I have what, from lines 13 to lines 56 so about 43 lines of code. Admittedly, I made this longer than it probably needs to be but notice the amount of duplicate code that I’ve introduced into the application. Here is where I am retrieving the first name and the last name and the city and those are essentially the same even though what I’m collecting is a little bit different but it’s only two lines of code so that doesn’t hurt much. Here we are actually taking the first name or the last name or the city and we’re going to do the reverse operation on it and we do that three times and there’s the third one. Then what we’re going to do is print out the results into a string called result which will then output in a console that right live. But notice here, we’re essentially doing the same thing here and here and then again here so there’s a lot of duplication. Now, duplicate code in and of itself is not a huge problem, there’s really no way you can completely eliminate duplicate code in your application but duplicate code is usually the result of copying and pasting code. You’ve invented the wheel earlier in your codebase and your first thought is, “Well, I’ll just copy and paste it because I need it here and here and here in my code.” Now, invariably what happens is your intent is to copy it but to make a few subtle changes to it and in your haste, frequently, at least if you’re like me, you will forget and you’ll make a mistake and forget to change something and you’ve introduced a bug and it can steal your soul like even if it’s just seconds. But what if it’s minutes or even hours of your time trying to figure out why you have a weird problem with your application? Copy and paste is dangerous, you should always treat it with great suspicion. But in addition to that, if you have the same code repeated multiple times, then whenever there’s a change that’s requested in how our application works, we’re going to have to change it in multiple places. But what if we were to take some of this functionality like this, for example, and this, and we were to extract it out and put it into its own method and then just call it three times? First of all, it would reduce our need for copy and paste. If we needed to fix a problem with our code, we can do it in one place, and then also, if we were to give that method a meaningful name in our system, it would describe what we’re attempting to accomplish. Right now, we’re just filtering through lines of code and it’s a little bit more difficult to ascertain quickly what this application is attempting to do. But if we were to maybe give our methods nice meaningful names, it might read more like a paragraph of English instead of a bunch of disparate lines of C# code. So that’s the goal. Now, the second reason we might want to break this up into methods is to simplify the readability of the code. We already talked about making it more human-readable but also, there’s a lot of lines of code here that we have to pass through to understand what’s going on and if we can reduce the amount of code to read, then we can improve the readability of our code. We want to reduce bloat every time we have the opportunity. We should strive to make our code readable, clean, clear, and perform well and maintainable so that if we need to make a change, we can do it in one place and methods help us accomplish all of those things. Let’s do this. Let’s create a method, we’ve already learned how to do that. I’m going to go somewhere between the end of our static void main but before the end of our program class, I’m going to define a private static void, ReverseString like so, and what I’ll do is copy some of the work that we’ve done here, for example, lines 24 and 25 and I’ll paste those here in our new method and then I’m going to copy the code that we used to actually print all these out to screen and I’ll paste those here as well in our reverse string method. Now to get started here just to make sure that this method is going to work, I’m going to hard code the message. I’m going to create string message equals Hello world and then I will change firstName to just message throughout and firstNameArray to messageArray and we’ll hit control period to rename like we learned about before. Then finally, what I could do is gather up all of the individual items printed out in reverse order using this foreach or I could just go here and go Console.Write each item like so and that’ll accomplish, at least for now, the same thing. Now that I have this working, I want to comment out everything I’ve done up to this point so that I can isolate, and then we’ll start reintroducing things back in as we get them working. I’m going to call the reverse string method by using the name of the method and then also again, method invocation operator and then obviously the end of line character and I’m going to go ahead and hit “Start”, and not a very exciting example but now we know that the logic of our reverse string method is working. What I’d really like to do is make this a reusable method. Currently, right now, it’s not all that useful. How many times do I need a print Hello world in an application? But if I were to remove this line of code here and replace it with an input parameter so that the caller can pass in the string that it wants reversed, now I improve the usability of this method dramatically. To create an input parameter, I need to give it a data type and then a moniker or a name. What I’ll do is say, I’m going to allow the caller to pass in a string and internally I’m going to call that string message. I’m creating essentially a variable that allows an outside passage of code to pass values into the body of my method. I can utilize that value inside of my method and then hopefully as a result of that, achieve some more interesting results. Now, having done that, I’ve changed the signature of the method. I used to have just a method called ReverseString but it accepted no input parameters but now I have to accept one input parameter and that’s not optional so I get this red squiggly line beneath the reverse string and if I were to hover my mouse cursor over, it’s going to say there’s no argument given that it corresponds to the required form parameter message of, and you’re like, “What does that mean?” Essentially, we did not call the method correctly now because we have to give it something like a hardcoded string, or probably the better thing to do here would be to give it the first name that we collect way up here in lines number 16 and 17. Let me uncomment that out and go down here and comment. Now I’m collecting the first and last name of the city but everything else I’ll leave commented out for now. Eventually, we’ll remove them and I’m going to call this reverse string method three times. Each time I’m going to change what I’m passing in like so. Now when I run the application, well, let’s do this as well. Let me copy that so that I can get similar results. Let’s go ahead and remove that and let’s see the application now. Make sure you have what I have on screen, possibly if you need to. Let’s run the application and let’s see it working and it should work similar to what we had before with fewer lines of code. It mostly works but you notice there’s a subtle problem with this. There’s no space in between Oak Park, Tabor and Bob. This is a good example of where I can make a change one place in my code and it will fix the problem throughout the code base, wherever I’m using and calling my new method. To fix this problem, all I need to do is to cancel “Right” and then add in a blank character that should allow sufficient spacing in between each call to reverse string. Now when I run the application and I put in my details, Bob Tabor, Oak Park. It should work correctly and it does great. Now this is definitely one way to go about writing this application. As I look at this method reverse string I see a problem. Typically, whenever I create methods, I attempt to describe in English what that method is responsible for doing inside of my software system. In this case, I would describe the functionality of this method as it reverses a string and it prints it to screen. But herein lies the problem, I really only want each method to do one thing in my system and when I use the word and, and print it to screen, I feel like that’s two responsibilities in the system. Typically, what I would do is split this out into two separate methods and you might say, well, that’s a little excessive, and that’s true in the simple case. But following that rule of thumb will help you as you begin to think about how to compose methods, what goes into a method? How many methods should I write? Should I create one massive method or lots of tiny methods? Typically the answer is more smaller methods with descriptive names are better. In this case, what we’re going to do is change up the functionality of the application a little bit. What I’ll do is take out all of this where I’m actually doing the writing to screen and what I want reverse string now to do is accept an input string and then return or report back, giving the result to the caller. In other words, right now we’re using the void keyword, which means I want you to go off and do something, but please don’t report back to me. I don’t care what you have to say, I don’t need to know anything from you, you just go, you work, you be quiet and everything is great. However, we might want to change this and say instead of being quiet when you finish your job, I want you to report back to me what the results were of what you did. In this case, I might want to say return back to me the reversed string. I’m going to give you a string and then what I want you to return to me is a string that’s been reversed. Notice when I added or changed void to string, I get a red squiggly line because I have not officially returned anything back to the caller. I need to use the return keyword like so. I could do a for each and gather up each individual item into a longer string like we done, pretty much previously right here by building that result. However, there is an easy way to do this with just one line of code, just like there is a helper method called Reverse on the array class. There’s also a string class, and the string class has helper methods too. One of them is the Concat method, and it will allow us to pass in an array of individual characters and it will concatenate them all together and return back a full string. In this case, let’s just give it the message array like so and that should work just fine. Now notice that I’m able to call reverse string and I’m not really accepting back any values. Why is that? I thought if we were going to say, Hey, report back to me that I would need to do something with it. In other words, I would expect to see something like this, where I’m capturing whatever has been returned from the reverse string method. That’s optional. I can listen for it and retrieve it and save it or do something with it, or I can ignore it. In this case, what I would probably want to do is actually save it, so I would call this reversed first name like so and then string reversed last name equals and then string reversed city equals. We’ll shorten this up in a moment. But hopefully you’ll see where I’m going with this. Then what I can do is console dot right. Right line or just here, let’s just do right. Reversed first name plus space. This seems laborious to do it this way. I’ve got a better idea the string has another helper method. We looked at the concat method, but it also has a format and the format will work a lot like canceled outright line. In fact, they’re almost identical. The only difference is canceled outright line will print its results to screen whereas string dot format will merely just create a new string as a result of whatever been formatted. But the reason I’m using this is so that I can use the replacement codes like so. Here I go 0, 1, 2 and I can pass in reversed first name, reversed last name, and reverse city like so. Since that is off to the right-hand side of my screen, I can’t easily see it. Typically, what I’ll do is move each of the input parameters to the method in this case console dotright. I’ll move in the separate lines to increase the readability. Notice that they’re indented a little bit. But this is all essentially one line of code, even though it’s spread on four lines. But it improves readability because I don’t want to have to scroll off to the right-hand side of the screen in order to read my work. Get in the habit of formatting your code for readability and keep things narrow and small. If they do go off to the side of the screen, don’t be afraid to move things down to different lines to increase the readability. Now let’s see what we have. This should work. Let’s run the application. It works great. But what if I want to put this into its own method? I could simply do that like so. I think I can just use a void in this case. What I could do is go display results and I could just take this and paste it in. But now what I need to do is pass in these three values. How do I go about doing that? Well, know how to add input parameter. How do we add multiple input parameters? What we’ll do is define our first one reversed first name like so then to add subsequent input parameters, I’ll just use a comma on the keyboard and add the second one like so and then the third one like so. Again, since it’s off to the right-hand side of the screen, I might put my mouse cursor right before the S in string and move those input parameters below the definition for our display result method again, for readability sake. You may not agree you don’t have to. That’s a stylistic choice. At this point, I should be able then to call display result. Let’s call display result passing in the reversed first name. I just happened to use the same names here, but I could have called either the input parameter something different or the temporary variables here something different. Reverse string, last name and as I’m doing this, I’m beginning to think to myself, why am I even going through all of this? Why do I even need these variables can I just eliminate those altogether and just copy this? Paste it here. I mean, it returns a string. I should be able to do that and I should be able to do this and I should be able to do this. Then I’ll put the Mitch on the line and that should work just fine and here I can eliminate these lines of code completely for my application. See if it works. Still works great, feels like this should probably go into this display result. That should reduce it from being there. Now suppose that I don’t want to pass in each of these individual values. What if I want to display the result and only pass in one value. What could I do in that case? Well, I can provide additional ways of calling a method by creating what are called overloaded versions of our methods. In this case, what I’ll simply do is I’ll start out and copy and paste the exact same method definition twice. Notice on the second definition, I get an error. Let me hover my mouse cursor over so you can see it, type program. That’s the class program already defines a member called display result with the same parameter types, you can create additional versions of the same method with the same name, but they have to have a different methods signature. A method signature is the number in the data type of the input parameters in your method definition. In this case, I already have a method called display result with three strings. I could change these names to just any old gobbledygook text there, and I still get an error. It’s the same problem because the fundamental fact that we’ve not changed the signature of the method means that I’m still having the same problem. However, I could change this by allowing only a single message or a single string to be input as an input parameter. Now I have two completely different versions of the method as far as C-sharp is concerned. Now, in this case, I wouldn’t need any of this. I probably just do this. Like so, and then I could call it by doing this. Basically what I was trying to avoid last time, but we’ll go ahead and do it anyway. This time we’re passing in one long string. Notice the use of the concatenation operator and the use of some empty spaces defined by two double quotes with just an empty space in between. We should have two lines that display essentially the same thing here. Let’s make sure we do this right. Well, in a WriteLine between them just to make sure there’s a break. Bob Tabor and we get two results that look identical. Now you might wonder why are we doing this? Why in the world would you ever want to create two methods with the exact same name that essentially do the same thing, but allow the user to pass in different information? Let me give you a good example of why you might want to do that is with the Console.WriteLine. Here we go with Console.WriteLine Have you ever noticed as you as you type the opening parentheses for the Method Invocation operator, that there’s a little message that pops up down there, there’s one of 19 and then you look to the right of it, and as I use the arrow keys on my keyboard to go up and down. Notice that the number goes one, two, three, four or five. These are all the different data types that the WriteLine method will accept, it’ll accept an input parameter of type Boolean, which is true false. It’ll accept a single character or an array of characters. It’ll accept a decimal value, which is usually used for money or a double, which is used for longer mathematical calculations or a float, which is a massive number in terms of the number of values after the decimal point. It allows you to pass in an integer and other types of integer style values. It allows you to pass in a string and then others as well 19 different versions of Console.WriteLine to make it convenient for the user of the application to utilize that method in their app for the developer, the application to use it in their app. Now when we go to display result, we’ll see the same thing in IntelliSense display result and notice that I have two versions. I’m looking at version one of two, and notice the emphasis on the input parameter that the first version accepts one input parameter of type string called message, and then the second version accepts three input parameters of type String, reverse String, reverse last name and reverse city. There you go. That is why you would create overloaded versions of your methods. Now, in this case, notice that we could eliminate so much of the code from this in order to essentially get the same working results, I’ll just delete that, and, for the sake of simplicity, I’ll go ahead and remove this as well. Now we’ve reduced down the amount of code dramatically for our application and improved the flexibility of our application by adding multiple ways to actually display the results. At Developer University, I issue a decree to students that no method should have more than six lines of code in it, if it has more than six lines of code in it, then it’s probably attempting to do too much in the system. You should be able again to express what it’s doing in English and then if you find yourself saying it does this and that, then it’s probably an opportunity to split those up into multiple methods. Of course, rules are meant to be broken, and as a rule of thumb, six lines of code per method will keep your code tidy and readable. It’ll keep everything scoped, nice and very tightly, and it’ll improve the quality of your code dramatically. That’s all I wanted to say about methods, but we’re going to be using them from this point on. If there’s anything about this that doesn’t make a whole lot of sense to you by all means, please make sure that you watch this lesson again or seek out some other resources. You’re doing great. Let’s continue on. See you in the next video. Thank you. Hi, I’m Bob Tabor with Developer University for more training videos for beginners, please visit me at w.com. In this lesson, we’re going to look at another iteration statement, the while iteration statement. Let’s just recap the iteration statements we’ve learned about up to this point. We’ve learned about the for loop or the for iteration statement and it allowed us to iterate through a block of code a number of preset times based on a counter. Then we also learned about the for each iteration statement that allowed us to iterate through a block of code once per item in an array. Now, in both of these cases, ahead of time how many iterations or how many times to iterate through the given block of code but what if you didn’t know up front how many times that you needed to iterate? Maybe you need to keep iterating until some condition is met. In that case, you’ll want to use the while iteration statement. Also, we’ll take a look at the do-while iteration statement, which allows us to always iterate at least one time before breaking out of the iteration statement. We’ll look at both of them in this lesson, and I’m trying to think of use cases where this would be useful. The most obvious one to me was creating some little menu system for our console window application. You’ve seen him before, especially if you’ve worked with DOS in the past. At any rate, what we want to do is begin with a new project you can see have already created it. It’s called WhileIteration. Again, another console window application. Please pause the video. Catch up with me. When you’re ready, let’s go ahead and get started by creating a method that will print out a list of options to our users in the form of a menu. We’ll do something like this. We have some more work to do here, but what we want to do is display this, so let’s just start by displaying the main menu here like so, and let’s run the application. Here we can choose an option. No matter what we choose at this point, our display will disappear. But suppose that we wanted to actually kick off another feature of our application, so say, for example, let’s go private static void of print numbers and then we’ll go private static void guessing game, like this and it will just console.WriteLine. Now let’s go ahead and call those from here. PrintNumbers and then GuessingGame. Now let’s run the application and we choose the first option and we’re able to play the print numbers game. But when I hit “Enter” we are completely removed from the application. What if I wanted to return back to that main menu? How could I go about that? Well, I could use a while statement to determine whether to show the menu again or to completely exit out of the application. To make this work, what I’m going to do is start off with a new data type called bool, we referred to it briefly a moment ago. It’s basically true or false. We want to create a new Boolean variable called displayMenu and we’ll set its initial value equal to true. Now what we’ll do is create a while statement. I’ll just type in while, tap tab. What I’ll say is while the display menu equals true, and then we will call display menu. Now a couple of things here. What we’ll need to do is actually then retrieve back for main menu, a Boolean, whether the user clicked “Exit” or not. What we’ll set is displayMenu equals MainMenu and then have MainMenu return a bool itself. Of course, we’ve completely broken the application at this point. That’s okay. Here we are going to continue to display the main menu until main menu returns the value false. If somebody chooses option number 3 to exit, then we might choose to completely exit the application, in which case we’ll return false. Now, if they choose some other option, like 4 or 5 or 6 or some other text option, then you might just want to redisplay the menu. We will return true again. Furthermore, we might want to return true as well here after we go through each of these options as well. Now let’s go ahead and run the application and see how it works this time. First of all, if we choose option number 1, it’ll display a message, and after we hit the “Enter” key in the keyboard, it will display the menu again and I can select number 2 and it’ll display the message and then I can hit “Enter” and now we can hit the “Exit” and we actually exit out of the application. What the while statement allowed us to do in this case is check for a condition and when that condition is true, then we can break out of the while loop. Otherwise, we’re going to keep executing the code inside of our code block. Now what we can do here is actually shorten this up a little bit. We don’t need to say, while displayMenu equals true, remember that just like when we’re using the if statement or the else if, we want to evaluate an expression and if an expression is true, then we want to either execute that block of code below it or not. In this case, if displayMenu is already true or if it’s false, we don’t need to actually do this evaluation. It already evaluates to true or false. We don’t have to do an equality there or check for equality. It’s either true or false, and so we can just write it like that very simply. Moving on. Now, what we want to do is maybe fill in the gap on some of these other little games we have here. Let’s play the print the numbers game. In order to do that, let’s go ahead and say Console.Write, type a number, and then int results equals Console.ReadLine. That’s going to return back a string, but what we really want is an integer. I’m going to go integer.Parse and this will allow us to take whatever string has been returned and convert it into an integer. Now we should have the actual integer value. Here what will do is create a counter for ourselves. Int counter equals 1 and then we’ll go while tap tab, the counter is less than our results. Then we will do a Console.Write with the current value counter. We’ll go Console.Write and we’ll do a little delimiter and then we’ll increase the counter. Now there’s a tiny bug with the application. We will come back to that in just a moment here. But let’s go ahead and run the application and let’s go ahead let’s type in a number 5 and it types in, and it will print out the numbers 1, 2, 3, 4. We’re able to change the number of times on the fly that will iterate through a block of code. Now it just so happens that this isn’t exactly what we wanted. Let me exit out of this. What we really wanted was to display from 1-5. I’m going to go ahead and add result plus 1. If I typed in the number 5, this would actually make this value 6. As long as we’re less than six, go ahead and continue to execute these lines of code. But once this statement becomes false, once the counter if it’s equal to 6, it will break out and will hit this line of code here in line number 59, the Console.ReadLine. That should work. Now, the other thing that I noticed when we ran the application is that we keep seeing additional data being written to the window. I might want to clear out everything that’s been displayed so far. Here we’ll start at the top and do Console.Clear, and that should clear off the screen for us. I’ll just copy and paste that here to print numbers as well. When we run the application again, this time I’m going to choose option number 1, and notice that it cleared off the screen and when the print numbers game, I’m going to type the number, let’s go 4, it types out 1, 2, 3, 4. I hit “Enter” it clears that off and it displays the menu again. Awesome. The next thing I want to do is play the guessing game. Again, here I’m going to go ahead and clear off everything that’s currently on the screen. What I want to do is choose a random number and then I’m going to allow the end-user who’s playing the game to try and guess the number between one and 10. How do I create a random number in C-Sharp? We actually use this built-in class in the Dunnett from the class library called the random class. We’ll create a new instance of the random class, we’ll talk about what that means, create an instance of a class, in an upcoming lesson. Let me do this. We’ll go random, my random equals new random. Again, that should make no sense to you whatsoever. That’s just fine. I’ll explain what that actually did in an upcoming class when we talk about classes. I want to get a random number from my random class, so I’m going to call the next method, and here one of the overloaded versions is that I get to give it a minimum value and a maximum value. The minimum value will be 1, but the maximum value, I want it to be 10. I’m going to say, don’t let it be more than 10. In other words, 11 is out of bounds. Now that I have a random number, I’m going to also keep track of how many guesses the player has guessed up to this point. Then I want to also keep track of whether or not the user was correct or not. Incorrect, and we’re going to say it is true that they were incorrect. Now watch this, I’m going to create a do while statement. I want the block of code that I’m going to create execute at least one time. That’s why I’m going to choose the do while as opposed to the while. The while we’ll evaluate the very first time and we may never actually run the code inside of our code block, but this time I want it to run at least one time. We’ll say, do this, but then at the very end, we’ll check for the statement while. If the while condition is true, then we can break out of it. While we continue to be incorrect is true. While we continue to be incorrect, then we’re going to keep guessing. Let’s start this Console.WriteLine and we’ll say, guess the number between one and 10. We want to retrieve that number. The string result equals Console.ReadLine. Now that we have it, we can do an evaluation. If the result is equal to the random number, so if whatever the user typed in is equal to the random number that we generated, then we want to break out of the wild statements so we’re no longer incorrect. In other words, let’s go ahead and say that incorrect equal to false. At this point, we guessed correctly and we’ll break out of the wild statement, and here we would want to say Console.WriteLine. Hey, you did it correct. However if they did not guess correctly, then what we would want to do is write Console.WriteLine and then wrong. We probably want them to guess again, which will happen because while incorrect is still true, then we’ll come and we’ll re-execute this block of code. Looks like a missing end of line character here. I can see that as I hover my mouse cursor over that little red area that I forgot a semicolon there. Otherwise, this should work. Now there’s one of the things that I want to do. I want to keep track of the number of guesses. Each time the user adds a guess, we’ve already initialized that value there, that variable guesses. I’m going to increase guesses or increment guesses by one. I type in the word guesses plus plus. That means I want to add one to the current value of guesses. Then here I want to type out how many times it took. It took you guesses, then like so. Let’s run the application. Let’s choose to guess a number between one and 10. We’ll start off at three. You can see it says it’s wrong, so I could continue to guess a number between one and 10. Let’s go 4, 5, 6, 7, 8. The number was eight. It took me six guesses to get to that. Now when I hit “Enter”, it returns me back to my main menu and here I’ll just hit “Three” to exit. Let’s go ahead and change our menu at this point. Let’s just do Print Numbers and then the Guessing Game. We’ve used the wild statement in a couple of capacities. The wild statement here is used so that we can continue to display the menu until the user decides to exit. We are using it to merely print out values to a screen, but we get to determine it at runtime or let the user to determine it at runtime as opposed to the four or the four each where it’s predetermined ahead of time. Then finally, we’re able to use the do while to continue to ask a series of questions until we get a satisfactory answer, at which point then we can break out of the loop. The do variation allows us to run our code block at least one time as opposed to immediately jumping outside of the block if the condition is true. That’s why we would use the while iteration statement. It’s pretty useful in certain cases. Let’s continue on. We’ll learn about strings in the next lesson. We’ll you see there. Thanks. Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. Now, many of the types of applications that you’ll build as a C-sharp developer will require you to work with text, whether you’re formatting the text for display to the end user or whether you’re manipulating the text in some way. A good example would be whenever you are massaging data. That’s a term that developers use to talk about taking data from a file or a database, and it’s in some raw form and you need to manipulate it. You need to remove certain characters. You need to add certain characters in certain positions in order to get it and prepare it for ingestion to be used by some other software system or to be saved in a different file format, whatever the case might be. Manipulating data is a key skill, whether for display or for the sake of massaging data into the right format. Furthermore, whenever you’re working with the string data type, you’re working with a data type that can hold a lot of information. To extend the bucket analogy, you’re working with a really big bucket. When you’re working with big buckets, you have the responsibility of working with them in an efficient way. Because when you’re working with data that takes up a lot of memory, it requires a lot of processing power, you are putting a strain on system resources. Now admittedly, it would take a lot of string manipulation to slow down a computer, especially a modern computer. However, software developers, we want to do things efficiently, and so it’s important to understand that there are tools in the dotNet Framework Class library that will help us work with and manipulate strings in a very efficient way. That’s really the purpose of this lesson. To show you how to perform some simple string manipulations like inserting special characters in your little strings, formatting strings, especially numbers and dates and things of that nature. Manipulating strings, changing things about string, searching for items and removing them or replacing them with something else and strings. Then also working with strings in a more efficient way. As you can see, I’ve already taken the liberty of setting up a new console window project called Working with Strings. Please take a moment, pause the video and catch up with me. I’ve already added three lines of code that we’ll use to demonstrate some key manipulations for our strings. What I wind up doing is just typing in a string and then showing you some manipulation and then moving on to the next line. But at any rate, let’s go ahead and start by talking about the special nature of the backslash character, which is that character there. I always used to get my characters confused. That’s forward slash, that’s backslash. A backslash character can be used to escape or insert escape sequences into literal strings. This will allow us to do things like put special characters, insert line feeds and things into a literal string. For a good example of this, what if I wanted to type something ironic like my so-called life? I wanted to insert a series of double quotes around the word so-called so that it displays the way that I would, as the author of this, expect it to be displayed on screen. Now unfortunately, you can see that the Visual Studio on behalf of the C-sharp compiler doesn’t like this at all. It thinks that you have two literal strings here. The word my and life and in between something that it can make no sense of whatsoever, the word so or the term so a minus symbol. Then the word called. These are not variables that have been declared. It doesn’t recognize them as keywords. C-sharp does not like this. In order to insert a special character like a double quote to say, I don’t want this to delineate a literal string, I want to use this inside of my literal string, I’ll use the backslash character before each double quote, which escapes out the double quote and makes it available for use inside of the literal string itself. Now when we run the application, we can get double quotes inside of our side of our string. Now similarly, let’s put in my string equals. I tell you what, I’m just going to copy this to my clipboard so I can keep using it. Now, what if I needed to add a new line? What if I need a new line and I want to split this up under two separate lines in my application? What I can do is insert a new line character. Think of a line feed. Slash n will create a line feed. Let’s go to run the application. You can see that it’s smart enough to know that even though we didn’t separate with spaces around the word a and new it was still able to find that escape character for the line feed and represent it correctly in our little string. Now, you might say well, that’s all well and good, but what if I need to actually use the backslash character? For example, in an instruction to go to your C colon slash drive, you’ll notice that we get a red squiggly line underneath the backslash because it’s expecting us to use the backslashes and escape character as an escape sequence. But we’ve given it nothing after that to indicate which escape sequence we want to use. In this case, we have two options. In fact, in all of these cases we have two options. We can use another backslash character to escape out of it to represent this correctly. Now you can see that you should go to your C colon backslash drive. I’ll just do this again. Go to your C drive. What we can do is add a at symbol in front of the literal string, and that tells C-Sharp that we want to use our backslash characters as true backslash characters, not as escape sequences or special characters. Let’s move on from there. We’ve already talked about the use of string dot format and we showed how we could do something like this, where we are going to insert the words 1st and 2nd into this template. The template contains a number of replacement codes. The number inside the replacement code corresponds to which argument is passed in to the string that format as input parameter. Let’s run the application and we would get what you might expect first equals second. What I didn’t tell you at the time was that you can actually reuse the replacement code multiple times. Like so or you can use them in a different order if you like. Let’s go back and change up the order where the second will be the first item displayed and the first will be the second item displayed, like so. Furthermore, the replacement code has some special powers. For example, if we want to do string.Format and say for example, that we wanted to display currency to the end user. I want to display $123.45 to my end user. In my case, since my computer’s culture is set to English U.S, this will be represented as dollars and cents but if your country and culture codes are set to for example, English U.K. or some other language and some other culture you would probably see something different whenever you choose to do this. You’ll see your native country and culture’s symbols for currency. But to create and format values for currency, you use the colon and then C immediately after the numeric replacement code. In this case, I’m using say zero still represents the first item in the list but the colon C says I want you to format it like currency. When we run it at least on my computer you’ll see dollars and cents with the dollar symbol. There’s all these little variations on this. For example, what if I wanted to just display a really long number to an end-user like 1234567890. I want it to look like a number not like how I have it here where you can’t really tell is that what, 12 billion or 123 million or what? To remove the confusion what you can do is use the colon and format character. This will add in decimal points and commas to give you the appropriate formatting for a large number 1,234,000,000 and so on. Furthermore, continuing that same thought what if we were to go string.Format and we wanted to represent a value as a percentage? What if I wanted to display this as a percent? Be sure to get those formatting codes in there. Just to show there’s nothing on my sleeve here, this is called as a percentage like so and then we will insert a percentage here. If this replacement code lets go and run the application and you can see that the percentage is 12.3 percent in this case. Finally, the last one I’m going to show you but I’ll show you where you can find more information is how to create a custom format. For example, in the United States, phone numbers have a very specific way that they’re presented. Let’s go string.Format and let’s go 1234567890. I want that displayed like a phone number so I would use zero and then I’m going to use count symbols to represent each digit that I want formatted. In this case, actually, I’m going to use parentheses around the first three numbers because that’s usually how an area code in a phone number in the United States is presented then a space then three more numbers then a dash then four more numbers. That’s just how phone numbers are presented in the U.S. Let’s go and run the application. You can see that it in fact formats that number the way that I would expect. Let me throw one little monkey wrench in this. What if I were to supply too many extra digits? I added another one two at the very end and yet I don’t have that accounted for in my formatting. Where will it be presented? Well, as you can see it pushes out the area code to five digits instead of just three. The moral of the story there is that the formatting will go from right to left whenever you’re using custom pound symbols to create a custom format for a numeric value. Again, the numbers will push their way out and once you get to the very end, it will put as many numbers as it can on that very first character and push that formatting out to the left. Be aware of that. The next thing that we want to do is start manipulating strings in a more meaningful way. Up to this point, we’ve been formatting strings but what if I want to actually change some things about the strings themselves? Let me start by providing a little something that we can sink our teeth into and work with. I’m going to type in a lyric from a song that I like. Notice that I added or I left in an extra space here at the very beginning of the string and then I left it in two spaces at the very end of that string. Let’s go. My string equals my string. I think the most important thing you want to realize about when you’re working with these data types is that they do have built in functionality that were provided to us by Microsoft. For example, every string has the substring helper method that we can use to just say, hey, I want to start at a specific point and then grab all of the characters within a given range. I can say start at position six and grab me back everything after position six. When I run the application you can see it starts with the word summer which is at the sixth position and grabs everything to the very end of that line. Here is position one, two, three, four, five, and six. It truncates off the first six characters and starts me there and I pulling everything else giving me a subset of the strings from that point on. But I can also say go ahead and give me the next 14 characters after that. Don’t give me everything to the very end of that string just give me the next 14 characters and so I can isolate a couple of characters in this case just three words in that string. I can also do something like my string.Toupper and that will do what you might think it will. It’ll make everything upper case. Great. What if I wanted to replace one character with a different character. My string.Replace and say find every blank space and replace it with a double dash like so. When we run the application, you see that we get double dashes instead of our spaces. It makes it more obvious that we had some spaces at the beginning and the end. We can also use mystring.Remove and we can remove a number of characters from our string. Instead of selecting out the substring of characters we took threes. We can actually remove those entirely from the string. You can see, summer we took it has been removed from the string completely. Also, what if we want to actually remove those trailing and preceding spaces? We could use the trim method. Let’s do my string equals, first of all, string.Format. Here I’m going to grab the length of the string to demonstrate this. The before length and then the after length. Let’s go mystring.Length and then my string dot will call the trim method to strip off all of the extra spaces in the beginning and the end. Or I could choose to trim off only the ending spaces or the beginning spaces but I’m going to call the trim method to get rid of it all and then determine what the length of the string is at that point. You recall that we used the length property whenever we were working with the array to find out how many items were in the array. We can also use the length property on a string to tell us how long the string is. That’s ultimately what we’re doing here. Tell me how long the string is before we make any changes to it and then after we trim off those extra spaces, how long is the string itself? Run the application again. You can see that the before was 46, the after was 43. We trimmed off three spaces. Great. The last thing I want to do is talk about working with strings in a more efficient way. For example, let me just type in a really quick code example here. We’ll just do this. Actually here. The mainstream plus equals. Hopefully you remember what this operator was for, where we’re saying, give me whatever the value of string is and concatenate everything on the right hand side to it. Here we’re concatenating on just double dashes and in the current value of i’s, we loop through 100 times and we’ll merely then just display my string in the console window. Let’s go ahead and actually get rid of that. We’ll start here with a blank slate. Let’s run the application. The output isn’t all that interesting, it’s just a printout of numbers with some dashes in there. But what’s going on behind the scenes is the more interesting part of this. What happens when you’re working with the string data type is that it’s called a immutable data type, meaning that you can’t just add more values to it. What happens behind the scenes is there’s this little dance that the dot NET Framework runtime is is performing to make it look like you’re still working with the original variable My Strings, the original bucket. But what it does is it creates a second bucket and it starts copying things over. In this case, it copies the previous value of My String plus any of the new stuff we want to put in there, and it creates this new string in a new bucket and then it removes the old bucket and it gives the new bucket, the name My String. Then we say, let’s do it again. In fact, let’s do it a hundred times and it has to go through that dance 100 times in order to produce the final result that we’re printing then in our console window. You can see that’s a very inefficient way and we’re requiring a lot of memory management that might put a drain on the system if we were to do a lot of it. Instead, what we can use is a different data type. Whenever we’re going to manipulate strings in this way, where we’re going to do a lot of string contamination or a lot of string manipulation, we can use something called a String Builder. Again, just like I said with a random class from the previous video, this may not make a whole lot of sense at first but hopefully once I talk about what classes are and how to create new instances of classes, this nomenclature that String Builder My String equals new String Builder. What is that all doing? We’ll talk about that very soon. But just let’s create a new String Builder class and then we’re going to do something very similar to what we did before where we will iterate through a 100 times. But this time, instead of just doing a simple concatenation, we’re going to use an append method, which is a more efficient way to append additional information to the String Builder object, rather than going through the previous step of forcing the runtime to create all these temporary versions of string. My String apend i and the result will look identical. But what’s going on under the hood is that we’re working with strings in a more efficient way. Use the String Builder along with the append method of the String Builder to work with strings in a very efficient manner. We talked about quite a bit in a very short amount of time how to work with the backslash character for escaping and inserting escape special characters into our literal strings, how to use string.format. In fact, let me show you this little page here for standard numeric string formats. If you just search for this on bin.com, you’ll be able to find this article and it gives you examples in many other usages for the format that we looked at several examples of here. We looked at several of the built-in helper methods to replace or define subsections or completely remove or actually create two upper or two lower to change the case of strings. Then finally, how to work with strings in a more efficient manner. Now we’re going to give the same treatment to dates and times because you’ll again find yourself working with dates and times frequently whenever you’re building applications and there’s a lot of similar functionality there as well. We’ll see in the next lesson. Thank you. Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at DevU.com. In the previous lesson, we looked at how to format strings and how to manipulate strings, whether it be for display or for the purpose of massaging data. In this lesson, we’ll do the same thing except for dates. We’ll start off by talking about formatting dates and times. We’ll look at how to add and subtract time to a given date. We’ll look at how to create a daytime object that represents this moment in time or the past or the future. Then finally, we’ll look at how to determine the length or the duration of time between two daytime objects. To begin, I’ve created a new project called Dates and Times. Pause the video, please and catch up with me. What we’ll do here is actually just create a new DateTime time object by going DateTime and we call this my value and we’re going to initialize its value to a valid DateTime. The easiest way to do that is to represent this very moment as the application is executing. We’ll go DateTime.Now and that represents this instant. The easiest thing that we can do is just do a Console.WriteLine, taking my value and calling the ToString method. Now you’ll see we have a lot of to something strings and we’ll look at a several of these in an effort to format our DateTime the way that we want. But this default ToString method will take our our country and our locale and will present dates and times as they are typically presented in our country and in our culture. Here in the United States, we usually represent the month first and then the date. I know most other countries it is date, month, year and then we have the time of afternoon that I’m actually recording the video. Notice that it also has AM, PM as opposed to military time or 24 hours. In order to change the way that this is presented, we’re given a bunch of other additional helper methods and so we can do something like this, myValue.ToShortDateString and this will just display the month, date, year. Isolate These short time string. Here we just want to display what time of day it is , 3:35 in the afternoon. Great. We can also choose a more long form version of the date. You can see it’s Tuesday, March 15, 2016, as I record this and we can do the same longer version for time as well, so myValue.ToLongTimeString. You can see not only do we have hours and minutes, but also seconds in the long time string. Great. Oftentimes what we’ll want to do is do some daytime math, which means we either want to add hours, minutes, I guess, to seconds, minutes, hours, days, months, years, whatever the case might be. But we can do it through a series of helper methods, the add methods. Here I’m just going to console.WriteLine and we’ll take myValue and we’ll start off with something simple, like AddDays. You can see that we can add milliseconds, seconds, hours, days and everything up from there. Let’s just do something simple, like AddDays. We’ll add three days and then we’ll just do it ToLongDateString on it like that. Now you may have noticed me do this in the past where I’ve

    used the period, remember, that’s the Remember Access operator and chained together a series of commands. In this case, we have a value that represents a date. If I were to call the AddDays method notices that hover my mouse cursor over it, that the return value of AddDays is another date time. Now, since I have another date time in my hand that represents today plus three days, then I can call that date times ToLongDateTimeString, which now returns as you can see a string data type. That’s the notion of chaining method calls together. As long as you continue to chain together methods that return some value of some data type, you can continue to call methods for that given data type. Let’s go ahead and see now, three days from now it will be, in fact, Friday, March 18th. Let’s do something with regards to hours and let’s go myValue.AddHours. We add three hours ToLongTimeString and that would be 6:38 PM. Then what if I wanted to subtract time? Are there any subtract hours or subtract days? No. However, what you can do is simply use a negative number to subtract, so instead of adding days, I’ll subtract days. We’ll just go ahead and run that. You can see three days ago it was Saturday, March 12th. Great. In addition, we can just grab off parts of a date or time. Here again, let’s go myValue, and let’s just pull off this current month. This will return an integer. Now, Console.writeLine we know can accept an integer, so we’ll just go ahead and print out the current month. The third month, obviously, that’s going to be March. Now, we’ve looked at how to create the current DateTime, but what if I wanted to create a DateTime in the past or in the future? I could do something like this, so DateTime and I’m going to call this myBirthday. Here again is that new keyword. I’ve hinted at a number of times, we will get to it, don’t worry, but I’m going to use it one more time, new DateTime, and I’m going to parse in the year 1969, the month December, and then the day the 7th, that was the day I was born. Now what I can do is something like we’ve been doing up to this point, Console.writeLine and just myBirthday.ToShortDateString just to prove that it’s of date just like the other dates that we’ve been working with, so 12/7/1969. Now there’s one final way to create a new DateTime, so let’s create another version of birthday equals DateTime.Parse, remember we’ve used in parse. We were able to take a string and turn it into an integer. Here we’re going to take a string and turn it into a date, hopefully. We’ll just type in myBirthday again one more time, and that should give us a DateTime object that represents December 7, 1969. Now what I’m going to do is try to determine how many hours that I’ve been alive or how many days I’ve been alive. Days is probably more interesting number. In order to represent a span of time, we’re going to use a new data type called TimeSpan. Here I’m going to use a new TimeSpan, and we’re going to call this myAge equals DateTime.Now.Subtract, and the subtract method will take the current date and subtract whatever date we want to use. In this case, we’ll use myBirthday. Now that I have an object that represents a span of time, I can say represent that span of time in terms of days or years or whatever the case might be. To do that, I’ll go Console.writeLine and then I’ll use this myAge.. Here I can say, give me the total number of days that I’ve been alive and print those to screen. You can see I’ve been alive, what? Well, 16,900 days. I’m getting old. I say that every time I record this video and I feel older every time. Anyway. Here we were able to format dates for display. We’re able to manipulate dates by adding and subtracting date and time, and they were able to determine the difference between two dates using a TimeSpan object. We also talked about different ways to create a date, whether it be now or some time in the past or future, by either just using one of the versions of the DateTime objects constructor, we’ll talk about that later, or by using DateTime.Parse and parsing in a string. Let’s stop right there and we’ll pick it up in the next lesson. Doing great. See you there. Thanks. Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. You might recall at the outset of this course, I said that a class is a container for related methods, and I used the console class as an example of this. We had the Console.writeLine, Console.readLine, Console.Write, we’ve even used Console.Clear. All of these methods that had something to do with working with the console window. I said it makes sense to put them all in the same class, the console class. Now, truth be told, I intentionally oversimplified my explanation about classes and their relationship to methods, because first of all, I wanted you to gain a little bit of confidence in yourself that you can do this, that this isn’t hard. You can get your hands around it and you’re going to do just fine. I wanted to do that before we got into the topic of classes, because while there’s nothing hard per say about classes, they do lend themselves to a conversation about object-oriented programming, a style of programming that some beginners find a little bit difficult to grasp at first. Now, the code that you’ve been writing in your methods have all been defined inside of classes, and you’ve been calling methods that were defined inside of classes. Classes have been all around you, you’ve been working with them from the first line of code that you wrote. You’re really already an old pro at this whether you realize it or not. I’m merely going to fill in some of the details that you don’t yet know about in this lesson in a couple of subsequent lessons so that it rounds out your knowledge so that you can fully harness the power of the.NET Framework Class Library in your applications. Maybe someday, whenever you sit down to architect some big application for some large company that you go to work for, you’ll begin to think like an experienced, object-oriented software developer. But at this early point in your C-Sharp experience, I really just want you to be able to do one thing and one thing well, that is to find what you’re looking for in the.NET Framework Class Library and be able to have the confidence to utilize the methods and the properties in those classes that have been defined there. The truth of the matter is that object-oriented programming is such a massive topic that I certainly couldn’t do it justice in this course. In fact, I have a whole course devoted to it on devu.com. Again, I really just want to accomplish one thing here, I want you to know enough about classes and objects and properties and methods and things like that so that you can harness the power of the.NET Framework Class Library inside of your own applications. Now, the way that we’re going to learn about classes and methods and properties and all that good stuff is by creating simple custom classes of our very own. Let’s start by talking about creating a simple application for a car lot. Suppose that I own a car lot and I want to sell cars, and I want to build an application that helps me keep track of all the cars on my car lot. I might need to create a number of variables to hold information about a given car, because I’m going to use that information to then determine its value based on its make and its model and its year and so on. I might start off by creating a couple of variables called car1Make, car1Model, car1Year, and so on, in order to keep track of that information. Now, what if I need a second car in my application? Well, then I guess I could create another set of variables called car2Make, car2Model, car2Year. What if I need a third one? Well, I think you see where I’m going with this, things are going to get out of hand pretty quickly here. Then what if I decide one day that the value of the car is not only based on the make, model, and the year, but we also need to keep track of the color of the car as well. In that case, now I got to do car1Color, string, car2Color and so on. You can see that this simply is not the right approach to keep track of information that should be collected together about a given entity. I need a way to keep all of this data about a car together in its own little container. I want to keep track of the make, the model, the year, the color, and maybe a bunch of other things too about a single car, but I don’t want to have to treat it like a bunch of loose information, I need it all related together. What I’m going to do is start off by defining a class that contains four properties that describe any given car on my car lot. To begin, what I’m going to do, you can see I have a project that I’ve already started with here, SimpleClasses, go ahead and pause the video and catch up with me if you like. What I want to do is work actually outside of the first class that’s already been defined in our program.cs file. I want to work inside of the namespace SimpleClasses, but I don’t want to define a new class inside of my existing class, I want to work outside of that class here, and so I’m going to define a new car class like so. I’m going to give it four properties, and I can type it all out like this and I’ll explain what I’m doing here in just a moment or I can use a shortcut prop, tab, tab and then I can use the replacement areas by using the tab on my keyboard, so I want to make a string, tab, tab model, enter, enter, prop, tab, tab, int, year, enter, enter, prop, tab, tab, string tab, tab, color, enter, enter. I’ve just defined a class name car with four properties. This car class allows me to define a data type that describes every car in the world. Every car has a make, a model, a year, and a color, and a bunch of other information that I might or might not be interested in for my specific application, but my aim here is to use this definition of what comprises a car in order to create additional instances of the car class that represent all of the cars on my car lot. In other words, I want to create a bucket in the computer’s memory that’s just the right size to hold information about any given car on my car lot. It should contain not only the fact that it’s a car, but then also the value of its make and its model and its year and its color, all in one big bucket up in the computer’s memory so that I can access it. There’s two parts to this. There’s defining the class itself and then once I’ve defined it, I can create instances of that class. Here the class is the definition, but when I create a new instance of this class, then I’ll be working with an object and sometimes those terms get confused. But the class is the blueprint, the object is an instantiation or something that’s been created as a result of having the blueprint or the pattern. The way that we create a new instance of the car class is to do this. I’ll just call this my car to avoid confusion. This point, I’ve defined it just like any variable I would by declaring the data type itself, whether it be string or integer. This is just a little bit more interesting, a little more complex. It’s the car class. Then I give it a name that I want to call it by my car. Now, that’s part of what I need to do. The next thing that I want to do is actually then create a new instance of that class and say, put this up in the memory, in the bucket, so to speak. Here we go, new car. Again, there’s two parts of this equation, we’ll talk about this more as we go throughout this course. First of all, I want to declare a new car in memory and then I want to create an instance of car and then put it up in the memory, so there’s two distinct steps there. In the real world, you can use the same blueprint to create many different houses. In the neighborhoods that I’ve lived in before, you might describe them as cookie cutter houses, they all look the same. You could use the same pattern to create clothing over and over, or you could use the same recipe to create the same cake or casserole and get the same results each time. Each time you want to build a new house, it will be at a different address. Each time you follow the pattern, you’ll create a new instance of the clothing that can be sold to a different customer. Each time you follow that recipe, you create a new instance of the recipe and you can offer it during either the same meal or a different meal. The same is true with classes, each time that you create a new instance of the class, you have a new object that is distinct and separate from the other instances of that same class in the computer’s memory. They each live by themselves. A class is like a cookie cutter. Now keep in mind, you can’t eat the cookie cutter itself. You eat the cookies that you make from the cookie cutter. The cookie cutter gives each of the cookies some shape, and so when you instantiate a new instance of a class, you’re basically using your class as a cookie cutter to stamp out new instances and you have 1, 2, 3, 4 new instances of cookies that you can then put in the oven and bake. Focus on the new keyword, it is what you would consider to be the factory. It actually builds the new car and puts it into memory. It uses the blueprint, it uses the pattern, it uses the recipe, it uses the cookie cutter in order to create a new instance of that blueprint or that pattern or that recipe or that cookie cutter and it brings the class to life in the computer’s memory, and it makes it usable by your application. You can create many instances of a given class or you can create many objects, all based on the same class, but each object will be distinct from the others. If by no other distinction then by is merely the address in memory where they live. What I want to do is not only set the properties of this car because I have these four properties that I want to use to distinguish this car on my color to represent this single car. But then also, I may want to then access or get those properties back out, and it’s working just like you’re working with variables. In this case, instead of just accessing make variable, I would go mycar.make and I would set that equal to Oldsmobile. Now, admittedly, in this particular case, I am merely hard coding these values. If this was a real application, I would ask an end user to input this information or I grab it from a database, something along those lines. There we have it. We have one instance of the car class and I’ve set all of its properties, and now I want to get those properties and print them out in a console window. We’ll just do this in the most easy way possible. We access, or we get the values just like we set the values before by using the name of the object, dot the name of the property. Let’s go make, myCar.Model, myCar.Year, and myCar.Color. Now you might be wondering, well, Bob, why did you do it that way and not Car.Make, or Car.Model? Remember car in that instance, car describes the class, the blueprint. But what we want to work with is one instance of the blueprint so that’s why we’re calling that instance myCar. It’s the variable name in the computer memory that we want to work with. Let’s go ahead and separate these out on the separate lines and then finally will go Console.Readline, so and this should not be an exciting application at all because we’re merely just printing things to screen. But at least I can show creating new instance of a class, setting the properties, and then getting the properties and printing them out. That’s what this get in the set are for. There are actually longer versions to declare a property in fact, let’s just do this propfull, tab, tab. This is a longer, more complete version of creating a property, but I don’t want to talk about it right now there are reasons why you would want to use this. But for the most part, for our simple needs, we’ll just use this abbreviated version of defining a property in our classes. Now did you notice that we got full IntelliSense support, so whenever I typed out myCar. and I used the member accessor operator that I’m able to see all the members of the class, the Make, the Model, the Year and the Color. All represented as a little wrench icons in IntelliSense so that I can access them, whether to set their value or get their value. Furthermore, I’m able to set values the way that I would just with normal variables by using the the assignment operator, I’m able to work with the variables and write them just like I would any other variable in my system. There’s nothing all that special about it outside of the fact that they’re all related, to a specific instance of a class. We created a new data type, the Car data type, and since the data type, we can use it just like we would any data type in our system, so if I wanted to create a little method here, private static, and I’ll use the decimal data type because I’m going to work with dollars or money currency, and I’m going to create a method called determine market value and I’m going to allow this to accept a car as an input parameter. What I’ll do is just in this case, I’m going to have to carValue to $100 and we’ll leave it at that. In fact, I’ll go ahead and the end here. However, if this was a real application someday, I might look up the car online using some web service to get a more accurate value. But for today, we’re just going to hard code the value to be 100 and we’ll return carValue. Here I can go determine market value, I can pass in myCar, and I should return back the value, so let’s go decimal value equals determined market value and then let’s go Console.Writeline and will use what we learned previously, to print out the value of the car like so, and let’s run the application. You can see that it’s worth $100. Now notice what I did here. I used the C in car in a c in car. The C corresponds to the name of the class because I named it with a capital C, and the C-sharp compiler is smart enough to know that again, C car and c car are two different things, and this is a common naming convention to use the same name for an object if there’s no reason not to. If there wasn’t something special about the car like it being in some special state, but I can reuse the word car, I chose not to do that here just to make it obvious what I was actually doing. But there’s nothing wrong with doing this as well. Defining this input parameters data type and then giving that input parameter the same name. But just with it lowercase character they’re two very different things. Moving on, I want to talk about creating methods on the class. We’ve already said that classes are containers for methods. We’ve created this helper method here inside of my static void main. But it might make more sense for us to create that method here inside of the car class itself since the car class already has access to information like the make model of the year and the color and that’s the information that we would use in making a determination on its value. Here, let’s go ahead and define this as a public decimal DetermineMarketValue. Now, we’re not going to allow anything to be passed in, because we already have all the information we need right here. Let’s create a little algorithm here. If the year is greater than 1990, then we will set the value of the car, the car’s value, which we need to define as a, so let’s go. Decimal carValue, set the carValue equal to $10,000 so if it’s a relatively new car, we’ll set it to 10,000. Otherwise, we’ll say the car’s values only words of 2,000. This is a very, very overly simplistic example. But we just want to demonstrate the fact that inside of an instance of the class, you’re going to be able to access its properties. We’re able to access the current car’s year in order to determine its value, and so in this case, what I’ll do is let’s comment this out and comment that out, and here will go Console.Writeline, myCar.DetermineMarketValue. Like so. Because this is going to come back as a decimal, I’m still going to want to format it. Now let’s go ahead and run the application. Since it’s in 1986, is before 1990, it’s only worth $2,000. In this lesson, we used a very concrete example. We’ve all seen cars, driven cars, own cars. A car is easy to conceptualize and represent in a class because there’s a tangible real world equivalent. Now my assumption again, is that your main exposure to classes will be whenever you’re using classes define by Microsoft in the.Netframe class library, and most of the time, those classes don’t represent real tangible things. They’re very conceptual in nature. You might have a class that represents a connection to the internet. You might have a class that represents a buffer of information that streaming from hard drive. They don’t really have real world tangible equivalence, so you need to be aware of that. In most cases, the.Net Framework class library classes don’t have real world equivalents, but the ideas are exactly the same. As you choose a software developer, you might want to invest a little bit more time in learning how to create your own library of classes, and those classes can interact with each other, they can represent real things in your company or in the real world or conceptual things. The process that you go through to break down a problem in the world and represented in objects, is object-oriented analysis and design. Again, that’s not a topic that we’re going to cover in this series of lessons, but you can learn more about that at DevEW.com, where I spend a lot of time talking about those things. To recap, a class is just a data type in.Net and it’s similar to any other data type like a string or an integer. It just allows you to define additional properties and methods so you can define a custom class with properties and methods, and then you create instances of those classes or rather you create an instance of in class, therefore working with an object using the new operator. You can then access that object’s properties and methods using the.Operator, the member accessor operator. There’s quite a bit more to say about classes. Don’t worry if you don’t understand everything just yet, why you even need them, how to really fully utilize them. Just make sure you understand the process that we went through in this lesson of defining a new class, creating an instance of a class, setting its properties, getting its properties, passing an instance of a class into a method, or even defining the method inside the class itself, and allowing it to access its own members like its other properties. If you really don’t understand much more than that, then you’re doing just fine. You’re exactly where you need to be don’t worry, we’ll cover lots of other topics related this in the upcoming lessons. We’ll see you there. Thank you. Hi, I’m Bob Tabor with Developer University for more of my training videos for beginners, please visit me at DEVU.COM. In this lesson we’ll continue to talk about classes and methods. We’ll begin by talking about the lifetime of objects so objects come to life. They live for a period of time, and then they die. They’re removed from memory, and we’ll talk about the.NET Framework runtime and its role in the creation, the maintenance and then ultimately, the removal of objects from memory. Next, we’ll talk about constructors, which are simply methods that allow us to write code as developers at the moment when a new instance of a class is created. Finally, we’ll talk about static methods and properties that study keywords been lingering around now for some time, and we’ve been using static properties and static methods throughout this course, even from our very first examples. So we’ll finally tackle that issue in this lesson. Let’s begin by creating a new project. You can see I’ve already done that and pause the video and catch up to where I’m at right now. I’ve created a new project called Object Lifetime. Furthermore, you’ll see that I copied the car definition from our previous lesson. If you like, you can type that in help build some muscle memory, help remind you to use the Prop Tab Tab shortcut, the code snippet in Visual Studio to create these short and auto implemented versions of properties. We’ve talked about that a little while, and then ultimately you can see in line number 13, we create a new instance of our car class. That new instance we’ll call myCar, and we’ve talked about this in the previous lesson, but I felt like this deserved a little bit more explanation because there is actually a lot that’s going on under the hood, and it would be helpful to understand this as we begin to work with classes and objects. Whenever we issue a command to create a new instance of a class like we have in line number 13, the.NET Framework runtime has to go out and create a spot in the computer’s memory that’s large enough to hold a new instance of the car class. Now that much we know. The computer’s memory has addresses that are similar to street addresses like the address you live at, the address that I live at. Now, admittedly, a computer’s memory address is looked dramatically different than our addresses, like 123 East Main Street, because the computer’s addresses are typically represented in hexadecimal values, but they’re known addresses nonetheless. It’s easy then, for the computer to find something in its memory by using its address. The.Net Frameworks first job is to find an empty available address where nothing is currently living, where there’s no data that’s currently being stored, and that address has to be large enough to store an instance of our class. The.NET Framework runtime will then create the object instance, and it will copy any of its values that are currently stored in that object instance up into that memory address. Then it takes note of where it put that object. It notes the address of the memory where it put that instance of our object, and then it serves that address back to us, and we store that address in the actual name or the instance name of our class. In this case, myCar, that variable is actually holding on to a reference or, in other words, an address in the computer’s memory where we can access that object once again. Now, whenever we need to access the new instance of the car class, we merely can use its reference name. It’s in this case myCar, so myCar is simply holding an address. It’s simply a reference to an instance of, in this case, a car class in the computer’s memory. Whenever you need to work with that instance of the car class, you just use the myCar Identifier and the.NET Framework runtime, takes care of everything else for you. It gives you the illusion that you’re actually working with the object itself, but in reality, you’re just holding on to a reference to an address in the computer’s memory. Now there’s an analogy that helps me to sort all this out in my mind, and we’re going to continue to extend that bucket analogy, if that object is stored in the computer’s memory, if it’s what we have equated to a bucket, an address, an area that holds on to our values, then what’s returned back to us as programmers is a handle, that’s what myCar is, it’s our handle to the bucket. We’ve used that bucket analogy in a number of different times and it’s served us well. But we essentially are storing values in that bucket just like we were before, and we’re holding on to that bucket using our reference to that memory area in our computers memory. What happens if we were to let go of the handle? Well, at that point we’ll no longer be able to get back to the bucket. We’ve lost the bucket somewhere in the computer’s memory. The bucket will no longer be accessible to us. Now, can we ever get back to that bucket? Well, no. What happens is that the.NET Framework runtime will be constantly monitoring the memory that it manages, and it’s looking for objects that no longer have any handles associated with them. Once we let go of a handle, the reference count, the handle count, I guess you could call it will go to zero and at that point, the .NET Framework runtime will say, I see that nobody’s interested in you anymore. They’ve let all of their handles to you expire or to go out of scope. That must mean that you’re no longer needed and it removes it and throws it in the garbage. That process of monitoring memory, looking for objects that no longer have any references to them is called garbage collection. It’s one of the core features of the .NET Framework runtime, and it’s one of the reasons why it’s easier to work with C-sharp at first as a developer than maybe going directly to C++. In an unmanaged language like C++, you, the developer, may have to manage memory on your own, and sometimes you might forget that you actually are leaving things in memory and you’re not cleaning them up, you’re not removing them yourself so your application might have a memory leak. Or you might have a corrupted memory region where you’re using an area of memory and you forget that you’re using it, so you copy something else to that area of memory. Now you go back to retrieve the value that you originally put in there, and it’s corrupted. That leads to corrupted memory in applications. You don’t really get that issue so much in C-sharp because again, the .NET Framework runtime takes care of all the memory management for you. Let’s do a little of experiment here, if we said that we can have one handle to a bucket, what happens if we attempt to create a second handle to the same bucket? Let me do this real quick. Let me go to myCar and start setting some of the properties like the Make equal Oldsmobile. Then we’ll set the Model equal to that Cutlass Supreme and then we’ll set the Year equal to 1986. Finally, we’ll set the Color to Silver. Now, keep that in mind, we’ve created a new object that we’re referencing using the myCar identifier. Instance of the car class lives in memory, and we’re holding on to it with a handle called myCar. But what if we were to create another car like this? So my other car, what have we really done right now? We simply have created a handle, but we’ve not attached it to any buckets of cars in our computers memory. At this point, what I could do is go myOtherCar equals myCar. Now, what have we really done there? Well, we’ve merely taken one handle to a bucket in memory, and we’ve created a second handle and said, “Hey, let me copy your address,” so that we’re both referencing the same bucket in the computer’s memory. Now, to prove that what I’ll do is do a Console.Writeline and we will do what we did before. Just give me a second here and we’ll reference myOtherCar’s Make, myOtherCar’s Model, myOtherCar’s Year and then myOtherCar’s Color. Let me separate these two different lines for readability sake. Then a Console.Redline for good measure. Now let’s run the application. You can see that even though we created or set the properties of myCar since we copied the reference to the car object in the computer’s memory into a new variable called myOtherCar, I can still get to the values that are in memory because they’re both pointed to the same object. Now I can even do something like this where I actually change something, myOtherCar.Model equal to the 98. That was the large style model for that car. Let’s then go back to and do something similar to this just to prove that they’re one and the same here, and I’ll say, “Hey.” Let’s do that. We’re going to use our reference called myotherCar and set the model, change the model from the value Cutlass Supreme to the 98. Then we’re going to say, Hey, show me what’s in the myCar object. So now we’re going to run the application, and you can see now we’re printing out what’s currently in my car. It’s the same thing that we changed in my other car because they’re both pointed to the same place. I just want to emphatically make that point here. As you can see, we have now two references to the same object in memory. We essentially attach the second handle to the same bucket so that we can use either one to retrieve the data in the bucket, so to speak. If you don’t like that analogy, maybe it helps to think of this in terms of balloons. I have a balloon and I have two strings tied to the balloon. What happens when I cut the first string? I’m still holding on to the balloon, but what happens when I cut the second string? The balloon now will fly away, and we’ll never see it ever again. As references go out of scope, in other words, whenever the current thread of execution leaves the current code block that we’re currently in, or those object references are set to null intentionally by the software developer, then the number of references to the object, the number of handles to the bucket, the number of strings attached to the balloon, they go to zero. So here again, when the. NET Framework runtime looks through memory and finds objects that have a reference count of zero it will remove those objects from memory. We talked about the two instances in which the connections to the object get removed. One is that the reference goes out of scope, so whenever we create a new variable called myCar, it will continue to be in scope as long as we’re inside of this main method. But once we exit out of the main method, that variable goes out of scope. it’s no longer available for us to access any longer. The same would be true if we created a different method, and defined a variable. As soon as we go out of scope of that method and we have finished executing all the lines of code in that method, then any of the variables that were declared inside of that method go out of scope. In this case, we would lose then any references to the objects that we created in the context of that method. That’s one instance in which we’ll lose references to objects that we created. But the second is if we, as the developers, actively take a role in cutting the strings or removing the handles from the buckets in memory. The way that we do that is by setting our objects equal to null. The value null is not zero, and it’s not an empty string, it just means indeterminate. In this case, what we’ll do is go here, and we’ll set myOtherCar equal to null like so, and when we do this now we’ll remove one of the handles to the bucket, so we’re back to just one handle in the bucket. To prove this, let me go ahead and copy this little section of code, and go here and put it below this, and when I do that, notice what happens will get an exception. The exception is that there’s a null reference exception that was unhandled, and the reason why it was a null reference exception is because we have now removed the handle. The handle does not point to any objects in memory, and yet we’re still attempting to access values from the object in memory, so we get an exception in our application. Now what will happen if we were to remove the second reference like so myCar equals null. Well, at that point now we have removed all the references to the bucket, even if we were to attempt to get to it with either myOtherCar or myCar, either way, the references are gone completely, and so now the object will be removed at some indeterminate time in the future by the.NET Framework runtime. In some situations, this indeterminate period of time can cause a problem, especially when the object in memory is holding on to some special resource, maybe something like a reference to a network connection or a file on the file system or holding on to a handle to access a given database. Again, we don’t know exactly when the.NET Framework runtime will actually execute the garbage collection step, and that might pose a problem in certain situations. In these cases, you would want to use a more deterministic approach to requesting that.Net removes the object from memory and, if necessary will finalize and clean up anything that needs to happen inside of that object to completely get rid of it in the computer’s memory. In these cases, you want to learn about deterministic finalization. That’s a little bit of an advanced topic, so we’re not going to talk about it in the series of lessons. Just keep in mind that whenever we set reference to null or whenever we go out of scope, we will be removing all the references to our objects. But the .NET Framework runtime itself figures out when it’s ready and willing to remove those objects from memory completely. In most cases, that’s not a problem. Occasionally, you’re going to run into a situation where it is a problem, know that there is a remedy for it called deterministic finalization. That should suffice our explanation of really what’s going on whenever we create new instances of objects, how objects are maintained in memory, and then at what point they’re removed from memory. Let’s move on and talk about constructors. I said at the very outset that a constructor is merely a method that allows us as developers to execute code at the moment that a new instance of a class is created. There’s something really subtle about what’s going on here in this line of code line number 13. Did you notice that whenever we use the new keyword, and we give it the name of the class that we want to create a new instance of that we’re also calling it using the method invocation operator. Why do you suppose that is? Whether you realize it or not, you’re calling a method whenever you create a new instance of a class, and that method is referred to as a constructor. It allows you, the developer, the option, you don’t have to do this. It’s an option to write some code at that very moment whenever a new instance of a class is created. Constructors can be used really for any purpose, but typically they’re used in order to put that new object into a valid state, meaning that you can use it to initialize the values of the properties of that given object, and so it’s immediately usable. Now, let me give you a really quick example here. Let’s say that you want to create a constructor that would allow you to set a property of the car at the point whenever you create a new car class. That property is available immediately in the very next line of code whenever we begin to work with it here in line number 15. Whenever you actually want to create a constructor, you would go and create something like this, public car. In this case, what I’m going to do is simply set the make property to Nissan. By default, whenever we create a new car class, we’re going to set one of its properties, the make property to Nissan. Now let me say this as well, you might see the keyword this used that this keyword is optional, it refers to this instance of this object, and it’s just to help clarify where this variable name or this name is coming from. When I see that this keyword, I automatically think, Oh, that’s part of the declaration of the class itself. It’s saying that you want to access a member of this class that’s been created. But as you can see, it’s faded out in my text editor. It might not be in yours, which lets me know that I could actually remove this it’s not necessary. You might see that though in other people’s code, just understand what that is. Now if we were to go ahead, and create a new instance of the car class, here’s what I’ll do. I’ll actually comment out all of this code. Like so, and then I’ll comment out the code that we know will break the application. We can leave the rest of it, I suppose. Notice that the very first item that is displayed is the make of the car, and it’s set to Nissan. I didn’t set any other properties. That’s why we didn’t get any other values there in the printout, but hopefully you can at least see how we go about creating constructors. Now, admittedly, it may not make a lot of sense right now why you’d want to do this, but I’m showing you the technique you’d use, not the rationale, necessarily, but the rationale is simple. What we would typically do here is to put any new instance of an object into a valid state. You could load values into the various properties of your class from a configuration file or from database or some other place in order, again, to get that object into a valid state so that it’s immediately usable at the point of whenever it’s instantiated. Let’s go ahead and talk about overloaded constructor. You’ll see this frequently whenever working with objects in the.NET Framework Class Library. Just like you can create an overloaded method in your classes by changing the methods signature, in other words, the number and the data type of the input parameters for the method, you can do the same thing with a constructor. You can create an overloaded constructor. What I’m going to do is create an overloaded constructor here like so. Now at this point, the method signatures are the same, so I’m going to get a little error here. But to modify that, I will merely add at least one input parameter of type string, but I’ll go ahead and do them all as well. Then here in the body of the constructor, I would Make equals make. This Make is in reference to the property itself. This ‘m’ in make is the name of the input parameter, and it’s a good convention to use the same name for readability sake and for your own sanity. You don’t have to do it this way, but just keep in mind that M and m are two different items as far as C-sharp is concerned. It’s not confused. You might be confused, but you will be able to handle this just fine. Now you might ask, what’s the point of that? Well, in many cases, whenever you create a new instance of a class, typically you don’t want to take five steps to do this. You would want to immediately whenever you create a new instance of a class, so my third car equals new car. At this point, you can do one of two things. Notice here that underneath the open parentheses, I have one or two ways that I can call the constructor. I can either give it no input parameters or I can give it four strings as input parameters to initialize that new instance of car and put it into a valid state immediately. Here I might go Ford, escape, 2005, white like so. Now I have not only created a new instance of the car class but I immediately initialized its values by calling its overloaded constructor to populate all of its values at the moment of instantiation. What would happen if we were to actually remove these two completely? What if we were to comment these out? What happens? You can see that we’re still using the method invocation operator for our new instance of car that would suggest that we’re calling a constructor, but we don’t have a constructor defined. Why is this working? Why isn’t it giving us an error? Well, the reason is because a default constructor is automatically created for you whenever you compile your classes. It will be a constructor without any input parameters and will have no body, but it’s essentially the equivalent of doing this right here, except with nothing inside of it. That’s created automatically for you. No matter what, you’re going to have a constructor, it just won’t do anything for you. The implicit default constructor has no input parameters, no method body, but it allows you to make calls and create new instances of classes in a consistent way. It’s actually just generated for you. Again, it compile time, of course, by defining it yourself, you’re taking control of the process of instantiation. Let’s talk about the static keyword now. You’ve seen static around since the very beginning. I said, let’s ignore that for now. We created our own methods, and I said, we have to use the keyword static. I’ll explain later. Well, now is the time. I want to ask a question, did you ever notice that whenever we were working with the Console window, we never had to create an instance of the console class in order to call its methods? That combined with the fact that whenever we wanted to work with DateTime, we could get to this moment in time by using the DateTime.Now property, but we never had to create an instance of DateTime. Furthermore, whenever we were actually working with arrays and we wanted to call the reverse method, do you remember we did Arrray.Reverse and then we passed in the array itself? How is it that we were able to use the reverse method without creating an instance of the array class? Well, in each of these cases the creators of those classes, or specifically those methods adorned their methods with the keyword static, which means that you do not have to create an instance of a class in order to utilize that method. In some cases, they may have defined an entire class as static, meaning that all of its properties and methods were static. You can create your own static methods in classes as well. Again, the objective here at the very outset is to just help you utilize the.NET Framework Class Library. So just know that some of the classes and methods in the.NET Framework Class Library are static and some are instance or require you to create an instance of the class before you call its methods and properties. Static methods will be available to you without first requiring you to create an instance of a class. Just so you can see how this works, we can create a static method on our car class like so. In this case, we’ll go public static void MyMethod, and here we’ll do Console.WriteLine called static MyMethod. Now we can go here near the very top and just say Car.MyMethod, and notice I didn’t have to create an instance of car. I’m using the actual car class definition itself when we run the application. Before we go too far here, let’s comment out pretty much everything. Let’s remove that. Let me go down here. Just make this so that we don’t run into any potential issues here. Let’s run the application and you can see that we were able to successfully call the static MyMethod. Now, what would happen if we attempted to reference one of the properties in our class? Let’s just print out the make property. Notice that I immediately get a red squiggly line beneath the word make. It says that an object reference is required for the non-static field, method, or property called Car.Make. It’s important to keep in mind that there’s a fundamental difference between working with classes that have static members versus instance members. Instance members are the things that we’ve been working up to this point where we have a series of properties that describe a single instance of a given entity like a car. They might be methods that operate on a single instance of a car like the constructors that we saw, whereas a static member, like a static method in this case, they don’t really operate on any single instance. They’re more like utilities. You can call them at any time. They don’t depend on the state of a given instance of the class or even the application itself, they can be used at any time because they’re not really tied to one specific car. They’re true of all cars and can be used at any time. Static members versus instance members, just keep those two clean in your mind. You might want to ask the question, why would you ever create a static member like a static method? Well, that’s a bit more complicated. That might require a longer discussion of things like design patterns which are common solutions to common problems for software developers or coding heuristics which are more the best ways to go about solving problems. I just want you to know that there’s a fundamental difference between static members in a class and instance members of a class and it’s easy to recognize them. If it’s a static member, it’ll have the static keyword and in which case you cannot reference any instance members like instance properties or even other instance methods that act on instance properties. They require an instance of the class to operate. Just know that there are these two types of members in a given class and that you’re going to encounter both whenever you’re working with the.NET Framework Class Library. Why you would use one or the other, well, that’s really again another story. I would say this that typically, I would recommend that you don’t mix and match them in the same class. Clearly, not everybody agrees with me because you’ll find that many times, but it’s not really important at this point to understand why you would use one over the other, just know that that possibility exists, that’s why you don’t always have to create an instance of a class before you use the members of its class; in this case, a given method. Let’s recap what we talked about in this lesson. We began talking about the lifetime of an object, how we create a new instance of an object, what that’s doing in terms of creating an area in the computer’s memory, returning back to us an address, a reference to that object in memory, what happens during the lifetime of that object, and ultimately, what happens whenever we remove all of the references to that object. Talked about the role of the.NET Framework runtime and how it’s keeping track of the number of references to objects so that it can perform garbage collection on objects that have no more references to them in memory as means of keeping things clean and making the memory available to other applications or even our application again. We talked about constructors and how developers can use them to put a new instance of an object into a valid state at the point when that object is created. Then we talked about the static keyword. We looked at some usages of static members inside of the.NET Framework Class Library. We looked at creating our own static member, this MyMethod. We talked about the difference between static members and instance members and how it’s really oil and water. You can’t mix the two and why that is. We didn’t really talk about why you would choose to use one over the other. However, that’s again a topic for another day. Hopefully, all of these concepts make sense. If not, don’t continue on and hoping that you’ll just catch up to them at some point in the future. Make sure you thoroughly understand this before you continue on. If you are continuing, great, we’ll see you in the next lesson. We’ll see you there. Thanks. Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. Now we haven’t spent a lot of time talking about variable scope. It’s actually extremely important. We recently learned that it also impacts the lifetime of objects. We want to spend a little bit more time really making sure we understand the scope of the variables, whether they be variables holding simple types or references to complex types in our applications. Not only do I want to fully explain that, but then I want to use that as a launching pad to explain key words like public and private that we’ve seen several times in our course up to this point but I haven’t really talked about. Before we talk about that, let’s talk about variable scope. Let me start by saying that whenever you declare variable inside of a block of code, that variable is only alive for the life of that code block and any of the interior code blocks or code blocks inside of that code block. Meaning that when the code block is finished executing, the variable that was defined inside of that code block is no longer accessible and its values are disposed off by the.NET Framework runtime. We’ll start by looking at how that is impacted by common code blocks that we’ve been working with up to this point and then we’ll use that and expand beyond there. You can see that I’ve created a project called UnderstandingScope and you can pause the video and catch up with me. I want to create this project and focus on testing how variable scope works. I’ll start with a pretty simple code example. Again, the concepts that we talk about also apply to object references not just variables that hold simple strings and integers. Let’s start by creating a simple for iteration statement and we’ll just loop through 10 times and we’ll do a Console.WriteLine containing the value of i, and then here, we’ll do the Console.ReadLine. We can see our results and we’ll run the application. As we would expect, we can see values from zero through nine. Now, what if I wanted to access the value of i here right after the closing curly brace for the for statement? We’ll notice that I’ll get a red squiggly line under i, and if I hover my mouse cursor over, it says that i does not exist in the current context. Why? Because i is now outside of the scope of its definition, we defined i inside of the for loop, it’s available inside the for statement itself plus in the code block below it but not outside of either of those. Let’s comment that up. Second, we’ll continue by going and creating a string of j equal to empty string. What we’ll do inside of our loop here is just go j equals i.ToString. Now let’s go outside of our loop where we’d be able to access the value of j. Let’s go outside of the four, and well, we’d we be able to actually print to screen the value of j. We were not getting any errors, so let’s run the application. You can see that the last value that was inserted into j was the value nine. Since we defined j outside of the scope of this of the for statement and its code block, we can access it inside of that code block and outside of that code block as well. Next up, let’s look at something like this, where we’ll actually create what’s called a field or a private field. We’ll go private static string k equals. A private field is like a property, except it’s private in nature, but it is available to all of the members of the class. We should be able to see k inside of our for loop. Let’s do i.ToString. We should be able to see it here as well outside of the for loop like so. Let’s go ahead and run the application. You can see that second Console.WriteLine will also display the number 9, but the real question is, what if we were to create a helper method? Static void, and we’ll just call this HelperMethod. Here we go. Console.WriteLine, and we’ll say this is the value of k from the HelperMethod, and we’ll do that. Now here, we’ll call the HelperMethod like so. Will this work? Will we be able to access the value of k as it was set inside of our for loop outside of our static void Main? Let’s run the application, and you can see that we can, in fact, get the value of k from the HelperMethod. Why? Because k was defined at, I guess, you could say, the class level. It is a sibling to static void Main and static void HelperMethod; therefore, it’s accessible to each of these as well as any of their inner code blocks. Hopefully, this is starting to make sense. Let’s go inside of the for loop now, and here what we’ll do is a simple if statement. So if i is equal to 9, so on the very last run of this, then let’s declare a string called l, and we’ll set that to i.ToString. Then outside of that, we’ll go Console.WriteLine the value of l. As you might anticipate, we will see that l does not exist in the current context. Why? Because we declared the value of the string variable l inside of the if statements curly braces. Outside of those curly braces, it’s no longer accessible, so we have to comment that out. Hopefully, this solidify in your mind many of the combinations that we can use in determining whether something’s in scope or out of scope. If you had any confusion about this, hopefully, that cleared it up a little bit. Now let’s move on to the larger topic of accessibility modifiers. We’ve been creating classes, specifically the car class up to this point, and whenever we were creating methods, I would typically use the public keyword. Occasionally, I would use the keyword private like I did here in line number 11. Private and public are both accessibility modifiers. They’re used to implement a tentative object-oriented programming called encapsulation, which is actually pretty important. In a nutshell, you should think of classes as black boxes. Whenever you think of a black box, maybe you can think of one of those old-style television sets. Maybe your parents or grandparents had one. I remember as a kid, us having one, there were no remote controls. You had to get up, walk across the room and actually turn the dials of the TV in order to tune to either VHF or UHF channels. You had another dial where you would adjust the volume. You had an antenna in the back, so you would connect this wire out to your antenna, and you had another one where you would plug it into the wall. Everything else about the television was self-contained. Now, as a kid, I was fascinated whenever my dad would pop off the back of the television set, and he’d go and try to fix it by changing up the tubes. It always seemed like magic to me because I knew absolutely nothing about the innards of televisions. All I knew were the public interfaces, the button for on/off, the dials to turn the channel, the dial to turn the volume up and down the antenna, whatever that did, and the little plug that would obviously give it electricity, but frankly, in order to use the television set, that’s all you really needed to know. You did not have to know anything about how a television worked. All you really needed to know is how to plug it in and change channels, turn it on and off, and then adjust its volume, and that is exactly how your classes should be treated. All the important behind-the-scenes functionality should be encapsulated behind interfaces like public methods and public properties. Now classes might, in fact, have private fields like we looked at here in line number 11, or they might have private methods that are used behind the scenes to enable all the magic that goes on inside of that class, but the consumer of the class shouldn’t know anything about the inner workings of the class in order to work with the class, to operate the class. All they need to know is what’s publicly exposed through the public properties and public methods. In a nutshell, private means that a method can be called by any other method inside of the same class. I used the term private HelperMethod a number of times accidentally. Essentially, when I use the term private helper method, I’m talking about a private method that’s add some additional functionality to those public methods that are exposed to anybody who needs to work with the class through that method. A public method is what’s actually going to be then called by somebody outside of the class, some other code outside of the given class, and private methods are only going to be called by members inside of the class. Let me do this. I’m going to paste in some code, recreate our Car class, and here I have a public and a private method. The public method is called DoSomething, and the private method is called just helperMethod. These are not very interesting examples. I want to keep this as simple as possible. Now, from the outside of this Car class, it’s just roll this whole thing up here and save it. Now, whenever I want to go here inside of my static void main, I might want to work with the Car class, so I’ll go, Car, myCar equals new Car, and then I’ll do myCar. and notice that I can only see the public method DoSomething. Now I might happen to know there are other methods also inside this class, but I can’t see them from outside. Their visibility is hidden to me because they’re marked as private. All I really need to know is how to use the DoSomething method. If I understand that I can call that, all the implementation details will be hidden from me, but it’ll work as I expect it to work. Here you can see that it’s merely prints out the words Hello world. Now, whose responsibility inside the class it is to actually display that? That’s none of my concern. All I need to know is how to call the public method DoSomething. In a sense, the consumer of the Car class has absolutely no idea that the helper method even exists. All it really knows is that there’s one public method and it could call that public method, but it doesn’t know any of the Harry implementation details. Now, I use the term in a sense that in a sense, the consumer of the car. The consumer is going to be a software developer and a software developer is going to be able to drill in and say, “Oh, I see how it’s doing its work. It’s actually making a call out to this other private helper method.” There is a sense in which it is public to developers, but it’s private from the perspective of the consumer, which is this main method. It can only see the DoSomething method, not the private helperMethod. That’s all we really mean here. Now admittedly, this is extremely mundane. It’s a simple example that’s only real value is to illustrate the notion of encapsulation, that we typically want to hide the implementation of our classes behind well-known public interfaces. In this case, a friendly method called DoSomething. The purpose of this lesson is to better understand the notion of scope because we said that once variables, especially variables that contain object references, fall out of scope, their objects will be garbage collected. Furthermore, it’s important to understand that there are parts of classes that you have access to and parts of classes that you don’t have access to. Now, if you ever decide that you want to create your own custom classes someday, even a library of classes that represent the business domain of your company or of your specific application, it could be a game, you should strive to expose public methods and give a simple, straightforward, obvious way to call the public methods from your class, but keep all the other helperMethod, all the other internals privately tucked away and not available to prying eyes. You don’t want a developer to simply go fiddling around inside of all of your methods and use your class in a way in which it was unintended. You want to give them a way to use your class properly through the methods that you’ve designed and that you’ve made available through public interfaces. This also will help to remove any ambiguity in the usage of your classes, and it should be much cleaner as well. All of these things were under consideration whenever the developer’s build the.NET Framework Class Library. In the.NET Framework Class Library, methods and properties are exposed using the public keyword. Now, they might also be using private fields and private methods behind the scenes, but you would never know. They may use other types of accessibility modifiers as well. There’s actually a couple available called protected and internal. However, these are primarily for whenever you’re working, either in a rich inheritance relationship between classes and you’re building a rich inheritance hierarchy between classes, or whenever you’re working with a very large library that’s compiled into separate assemblies. That’s when some of these other accessibility modifiers might come into play. They’re topics that are beyond the scope of this absolute beginner series, but topics that I do cover on Developer University. If you want to know more about object

    oriented programming and encapsulation by all means, go ahead. We are well past halfway through this course. You’re doing great. We’ve already covered the most difficult material already, now we’re just adding on details, so you should be encouraged by that, that you’re still plugging away at this and you’re doing great. We’ll see in the next lesson. Thank you. Hi, I’m Bob Tabor with Developer University. For more my training videos for beginners, please visit me at devu.com. Previously in this course, I said that the .NET Framework Class Library is merely a collection of classes, each containing methods filled with functionality that we can utilize in our applications, but we didn’t have to write. Microsoft has spent tens of thousands of man hours building and maintaining this library of code, and we can benefit from it by merely calling into his classes and methods inside of our applications. Now, the Framework Class Library is massive. Thousands of classes, each with their own set of methods, and so the developers of the Framework Class Library wisely decided to split this library of code up into multiple files. Just imagine if you had to load the entire library into memory every time you wanted to run your application. First of all, it would be excruciatingly slow. Then secondly, it would probably take up the maturity of your computer’s memory. They split up the code into multiple files. These code files are called.NET assemblies. In fact, even the applications that we build, they’re ultimately compiling into.NET assemblies. As you can see, I have a new project called AssembliesAndNamespaces already open. I’ve added two lines of code. If you want to pause the video and catch up, that would be great. In lines 13 and 14, I’m merely printing Hello world to the screen and then pausing the execution of the application. However, even in this application, a executable.NET assembly is being generated the very first time that we run the application while we’re debugging. Now, if you want to take a look at what happens, go to your project’s directory and inside of the project folder, you’ll see that there’s a bin directory. We avoided this very early in this course, but now I want to talk about it briefly. The bin directory will contain both at a bug in a release version, ultimately a release version. The debug version will contain additional files required by Visual Studio to connect to the execution of the compiled executable. This allows us to step through the execution and pause the execution line by line in the Visual Studio debugger. Now, we can additionally, then after we created our application and thoroughly debugged it, we can say I want to create a release version of the application and go to Build Solution in the Build menu, and it will create a version of our application without any of those debugging symbols without that connection to the debugger. If you look at the file system, you might be a little confused to see that it also has a lot of those extra files in there, but they’re basically ignored. But that is what’s going on behind the scenes. Notice that in each of these cases, we’re building an executable file that will run and we could even just double click it and run the application from here like we did before. Now that is different from the type of.NET assembly that allows you to create a library of code that can be shared across multiple projects. In that case, you’d be compiling a project into a.DLL file extension. We can create a code library. I’ll show you how to do that in another video. But at any rate, the.NET Framework has to already be installed on any computer where you want your application to work or to run. Basically, every copy of Windows already has the.NET Framework runtime and the class libraries installed in a location that’s globally accessible, called the global assembly cache. Every.NET application can reference the same set of assemblies in that one spot on your hard drive. Now, you might say that whenever you build your application and set up your application, you may not realize that by choosing to create a file new project and then selecting the Console Window project template, you were actually creating references to those files in the .NET Framework Class Library. That’s one of the functions of the setup routine for a project template. If you take a look at the references node underneath your project in the Solution Explorer over here on the right hand side, you’ll see that, there are some references already to these things like system, System.Core, System.Data, System.Net and so on. We’ll talk about what these are in just a moment, but that’s indicative of the fact that we have references into files of the .NET Framework Class Library that the creator of the Console Window application thought we might be or might find useful at some point. We’ll come back to that in just a moment. Now sometimes you’ll need an assembly from the .NET Framework Class Library that has not been referenced and I’ll demonstrate how to do that in an upcoming lesson. Or perhaps you need to add a reference to an assembly created by a third party, maybe even yourself. Again, I’ll demonstrate not only how to create your own class library, but then also how to create references to third party assemblies as well. Again, there are 10’s of thousands of classes defined in the full.Network framework class library. In a few cases, the same class name was used, or at least there was the potential for it to be used. When that happened, the creators needed a way to be able to tell one class from a different class and so they introduced the notion of name spaces and name spaces are like last names for your classes. Think about your name or my name. For example, somebody might say, “Bob loves coffee” You might say, “Well, which Bob?” There’s like a billion Bobs in the world. But if somebody were to say, “Robert Theron Tabor likes coffee.” Well, that narrows it down. I’m pretty sure that I’m the only person in the world that has that combination of first middle and last name. I could either use the full name, Robert Theron Tabor to reference one person or once we understand the context of who we’re talking about, maybe we’re talking about only people in this room. Then you might say, well, Bob likes coffee, he’s the only Bob in this room, so they must be talking about Bob. The same idea works with your code. We could use the full name of the classes that we need inside of our application. For example, the full name of the console class is actually System.Console.WriteLine. Or the System.Console class. That’s the full name of the class and then we’re calling the method in that class. However, you’ll notice that I didn’t have to use the Word system here. Why not? Well, because we used a using statement at the very outset of this code file, which says, ‘I want you to look inside of these name spaces whenever you find a class reference that you don’t recognize and so the C-sharp compiler, it finds the Word Console and it says, “Hmm, I wonder where that came from?” It begins to look through the name spaces listed in the code file and it says, “Oh yeah, I found a class name called Console inside of a name space called System.” So it thinks, “All right, well that must be the Console class that he’s talking about.” Occasionally, you might have two classes with the same name, and you’ve added using statements for each of these inside of your code file. When that happens, you merely need to disambiguate by adding the full name of the class instead of relying simply on the using statement. You’ll notice here that by default, the program that CS file has a number of different using statements. In my text editor they’re faded out a little bit, which indicates to me that they’re not being utilized at this moment. We could remove unused using statements from our code and our code will compile just fine. This is a convenience for us, that was set up for us by whoever created the project template for a console window application. To further illustrate this idea, let’s talk about how we can go about using the.NET Framework Class Library to do meaningful things and how we would go about finding the source code or the classes we need to do something cool in our application. For example, maybe I want to write data to a text file. How could I go about doing that? Well I might open up bing.com, and I’m going to type in site:Microsoft.com, so I’m going to limit the search results to just those that are returned by Microsoft.com. This is going to help me find the documentation specifically created by Microsoft as opposed to third party articles or whatever the case might be. So site called Microsoft.com and then I might just say, write to a text file and then using C-sharp. One of the top results are from msdn.Microsoft.com and msdn stands for the Microsoft Developer Network. This is your primary source of information as a software developer on the Microsoft platform. In this case, here’s a how to article that will describe the code that we would need to write in order to write data to a file. Here’s a long code example. In fact, it gives us three examples in one and we could use one of these examples in our application in order to write data to a file. We might decide to go ahead and use the second example. It comes close to what we want to work with here and I copy and paste it into my application and I might remove some of the extra information here just because I don’t need it and I may need to modify this path. I believe I created a folder called Lesson 17 for this purpose. Notice that it’s going to use a class name file and a method called write all text. In this particular case, notice that we already are given the full name name space of this file class, System.IO.File. What we could do is actually remove that from here and go up and add a using statement for System.IO like so. Notice that, the compiler will find it and will be able to run our application and got a little message there because I was in release mode, lets go back to the bug and start that over again. We don’t get any feedback there but if we were to open up our Lesson 17 folder, we would be able to find the text in a text file. Great, so now we can use that little snippet of code to do what we want to do, but notice it all started by searching on msdn finding a code snippet that we could use and then we can modify it and add our own text here that we want to then we want to write this to our file, so that we start stitching things together. That’s one way that we can find the features inside of the.NET Framework Class library that we need is to search on msdn. Let’s try one more quick example and let’s go back here, back to bing.com and here again I’m going to cycle in on Microsoft.com. Then I want to do c-sharp download html as a string and I might find another reference. This is a different style web page. There is one web page on msdn for every class and every method in the.NET Framework class library. In this case, we’re looking at a specific page for this download string method and if you were to look at the remarks and some of the additional, the syntax and some of the exceptions that it would throw, what we ultimately get to is a little snippet of code that we can copy and that we can paste inside of our application. That’s what happens this time, it does not recognize the term WebClient. Why not? Well, we may not have the assembly referenced in our project, or we may have the assembly referenced, but we do not have a using statement that would include the WebClient class. To remedy this, I’m going to hit “Control period” on my keyboard, and it says that it found this class in system.Net so we can automatically add a using statement for the System.Net class by merely hitting the “Enter key” on my keyboard. Or I can just go ahead and say, let’s go ahead and use the full name of the class here, I’ll choose the first option using the Arrow keys and the Enter key on my keyboard. Notice what happens, it adds a using statement for System.Net and then notice that the WebClient class is now found. It is obviously in a different color, there’s no red squiggly line, so it looks like it found the correct class that we’re looking for. Now we merely need to give it a URL so let’s try, msdn.Microsoft.com like so and then we will just write this out to string reply. Then we might even rework our application in attempt to save that into our text file as well. Let’s see what we get here. Hopefully, this will work, we’ll run the application. It took a moment, but it loaded up a bunch of HTML into our console window. We can see the closing body in the closing each HTML tag. Now, if we were to go back to our folder and find our Lesson17 folder, and open up our text file, we see here is the full web page that we scraped off of msdn.Microsoft.com. That pretty much wraps up what I wanted to say in this lesson. We are able to utilize the classes and methods in the.NET Framework Class Library and we can find what we need by doing simple searches in bing.com using Psyco and Microsoft.com to find the classes in the methods that we want to work with. Once we find those classes that we want to work with and we find maybe even little code snippets, we can copy those into our program, and we may need to at that point, fix the references to those classes. Now, in this first case, remember that it gave us the full name of our file class System.IO.File. But in the second case, we had to provide the using statement, System.Net in order for the compiler to find the class that we were wanting to reference and work with. Ultimately we did that with hitting “Control Period” in the keyboard to add a using statement to the very top of our code. We talked about the purpose of namespaces to provide disambiguate between class names. We talked about the using statement as a way of creating a shortcut or a context and say, we’re not talking about every class in the.NET Framework Class Library. We’re only talking about the classes that happen to be in these namespaces. If you find Mr. C# compiler, if you find a class that you don’t recognize, look in those namespaces first before you complain. We’re going to continue on these ideas in the next lesson. We’ll see you there, thank you. Hi I’m Bob Tabor with Developer University, for more of my training videos for beginners, please visit me at DevU.com. Now, previously I said that the creator of the console window application project template, added references to those assemblies in the.NET Framework Class Library, that we as developers might find useful for the majority of use cases. However, if we need an assembly containing some portion of the.NET Framework class library, that has not already been added to our project, then we can simply add a reference to it. This is one of three ways that will demonstrate how to add a reference to an assembly. The first being an assembly from the.NET Framework Class Library. Now there’s a number of different ways to go about this. The easiest way, I think, is to go to the Solution Explorer, and then right click on “References” and select “Add Reference”. Here you can see there are a series of, I guess, tabs along the left hand side that would allow us to choose from the various types of assemblies that are available to us. We want to choose the Framework and these are all of the assemblies that are part of the.NET Framework Class Library. Now, and you can see that there’s already check marks next to a number of the system.this, system.that, System.Net.Http. These contain a number of different classes each with many methods, and these are just automatically accessible. If we needed something that is not contained here then we could choose, for example, to just select a checkmark next to the one that we want to add to our project System.Net and click “Okay”. You can see that is added a reference to System.Net into our project in the Solution Explorer. Now we can reference any of the classes and utilize any of the methods in that particular assembly. That’s one way if we need to access some part of the.NET Framework Class Library. Now, in addition to that, there are libraries that are created both by Microsoft and there are libraries that are created by open source contributors, other companies that are provided for free for very specific purposes in our applications. These are often common features that many applications need that’s why they’ve been open sourced. However, they’re available through a special tool called NuGet, which is a repository that’s maintained by a foundation supported by Microsoft, but ultimately its own entity. There are a number of different ways to work with NuGet in Visual Studio, I’m going to choose the visual way to do it. I find that to be the easiest for those who are just getting started and for me, because I’m a more visual person. There’s also a textual, almost command line style interface that would allow you to do similar things and even script these things. Let’s go to the tools menu and select “NuGet Package Manager” and then “Manage NuGet Packages for Solution”. This will open up a tab, undoubtedly no matter what you see on my screen, it will look different on your screen because this is going under active development for the last few years, and it has changed frequently. Now, if there were a package that we wanted to add to our solution, we could simply search for it. Typically, we can learn about these things through blog posts and what have you. Say for example, I wanted to access a database from my console window application, and I wanted to use the Entity Framework API from Microsoft. It’s available as a NuGet package through this Manage NuGet Packages for Solution dialog. I can select it as one of the options you can see it’s one of the most frequently downloaded. Furthermore, I would then choose which project in my solution that I wanted to add it to, and I can choose the “Install” button. There’s some other options as well, I’ll leave you to to investigate those on your own. I’m going to go ahead and click “Okay” I agree to the terms for using the Entity Framework. In this particular case, it installed just a number of references to assemblies and copied them down locally to my computer. Now, depending on the type of package, it could not only contain.Net assemblies, but also sample source code files. It could actually run macros inside of Visual Studio. It could include things like style sheets and HTML, and even graphical assets that it will include your project. This is the second way that we can go about adding assemblies and more to our projects. But the third way that I want to talk about is whenever we want to add a reference to a class library that we created. Now we haven’t created a class library up to this point, so this is a perfect opportunity to do that and then add a reference to it in our project. What I’ll do is start off by creating, New, Project. Let me go ahead and let you see my entire screen here. In the New Project dialogue, I want to make sure to choose C#. Then I want to choose Class Library, notice that I chose the one that doesn’t have a little Nu.Get logo next to it, it’s just looks like several books in the old C# logo. Now, this will undoubtedly look different to you, but just make sure that it’s a regular old class library. Here we’re going to call this MyCodeLibrary and click “Okay”, and I’m going to go ahead and say, I don’t really care to save my other solution there. Inside of this, you can see that I don’t have a program.cs, all I have is a Class1.cs. There’s no static void main, and so what I’ll call this is the scrape class, and we’ll have one public method, so public string ScrapeWebpage and we’ll create a version of this where you provide it just the URL. Then we’ll create a second version of this. Where you provide the URL and file path. In this first case, I’m just going to copy down some of the code that we’ve worked with previously to create this functionality, where we were actually using this webClient to go out, download a page and then save it to a text file. I’m just going to generalize this. Remember what I did previously when I hit “Control Period” on the keyboard in order to add a reference to System.Net or add a using statement for System.Net? The next thing I’m going to do here is actually replace this hardcoded string with whatever gets passed in by the end user. Finally, I’m also going to have to add or resolve this reference to the file class. It’s in the System.IO namespace, so I’m going to add a using statement for that. However, in this specific case, I’m not going to write this to a file and this overloaded version of it. In fact, what I’ll just do is return whatever’s been actually downloaded from client.DownloadString. Now, the second version, we’ll do something almost identical. Here, let me replace this with the URL, and we’ll get rid of Console.WriteLine and we’ll go ahead, and write this to the file path that was passed in and then we’ll return the reply. Now, truth be told, this might be a good situation where I could actually take these lines of code and create a private helper method out of them. Maybe that’s a good idea, let’s do that right now. Private string GetWebpage and we’ll pass in the URL here. Now both of these can just call, GetWebpage like so. Here we’ll go string return or reply, equals GetWebpage. See what I did there. I was able to use a private helper method to encapsulate the functionality of actually getting the web page itself, and then in this case, I was able to extend the ScrapeWebpage method to include writing that to an actual file path. Now that I’ve created this, and let me go ahead and rename this file as well by right clicking on it and selecting Rename, and I’m going to choose to name this file scrape as well. I could name it anything I want, it won’t matter, because the name of the class itself is scrape. But at this point now I’m going to go ahead and build the solution. It looks like it built. In fact, let me go ahead and build a release version of this. Great. Now let’s open up a second version of Visual Studio. I’m going to call this MyClient. This will be a console application called MyClient, and we’ll click “Okay.” What I want to do, is to first of all, add a reference to that deal that we created just a moment ago. I’m going to go in right click on references and select add a reference. Here I have some choices. Ideally, I would be able to look and find it in the same solution, will come back to that and do it in just a little bit here. But I may have to go and actually browse through the file system to find this, and unfortunately, this is popping off the screen. However, hopefully we can work our way through this. I’m going to navigate to the bin directory into the release directory and find my code library, and then I’m going to select the “Add” button and then click “Okay”. Now that I’ve done that, what I should be able to do is get to the scrape class, but it doesn’t see this scrape class. I’m going to hit ” Control” “Period” on my keyboard, and notice that it will find the correct using statement. The Using MyCodeLibrary namespace. Scrape myScrape equals new Scrape. Now I should be able to go myScrape. and there we go, ScrapeWebpage and I should be able to give it a url. Let’s go. That should return a string. String return or actually just value equals. Let’s move this over a little bit. Then I should be able to print that to screen. Console or write. Now we should be able to run the application. It takes a moment, but it pops up. What we’re able to do there? Well, we created a reusable library now. Whenever we want to scrape a web page, we can utilize this and any of our other projects. Now did you find how inconvenient it was to actually go and search around whatever we wanted to add a reference to it? I had to go, and browse through all my projects and everything. But I do want you to notice one thing about what happened after we did that. Let’s go to my projects. Let’s find that client and let’s navigate into the bin directory. Notice that it copied MyCodeLibrary.dll into the bin directory for the client application. That’s one of the things that it will do with any of the third party assemblies that it we’ll utilize. But wouldn’t it be easier if we were to start this over from scratch, and we were to create a single solution that had both the client and the code library in the same solution. Let’s do that now. I’m going to actually open up a third copy of Visual Studio. Here, let’s create a new solution. What I’m going to do is actually scroll all the way to the bottom and choose other project types, and choose Visual Studio Solutions, and find a solution. This might be in a different place, so you may have to hunt around for it, but you ultimately want to choose blank solutions that should be available to you. We’re going to call this a Lesson 18. The solution’s name will be Lesson 18, but we’re going to do is add projects to the solution. The first project that I’m going to add, and there’s a number of ways to do this like add, but it goes off to the right hand side of the screen, I could add new project, file add New Project and then we’re going to choose the class library. We’ll call this the ScrapeLibrary. Then I’m going to choose to create another project and add it to our solution called app type Console Application. This will be the ScrapeClient. In our ScrapeLibrary, what I do just for simplicity’s sake, is actually go to the work that we’ve done here a moment ago, and I’m going to copy all of this like so. Let’s come back here, and I want to paste all this in, like so. Yes, I’m going to have to resolve these class names by adding using statements here and here as well. That should work. Looks like I actually lost my class name, so let’s go public class Scrape. Then let’s make sure to put everything inside of it. There we go. Now we get it working, and I’ll rename this as well to just scrape. I could have left it, call the class one to but that’ll work just fine. I’m going to go ahead and build that right clicked on the project name a select to build. Now what I want to do in the client to utilize that class library, is I need to add a reference to it. So here again, I’m going to right click and select add reference. This time we go to projects, and notice if solution is selected, the Scrape Library will be an option. I’ll choose that and click “Okay.” Now we can utilize ScapeLibrary in our application. Let’s go ahead and just type in the “Word” scrape., and it’s not going to find it. The Here Control period, and I need to add a using statement, since I renamed it. Now it’s called ScrapeLibrary. I’m going to add the ScrapeLibrary namespace too, using statement to the code file. In fact, I don’t have to do all that right. I can just copy and paste it from the previous client, like so. We can rerun the application. It says a project with an output type of class library cannot be started directly. Why do you suppose that happened? Well, because there are actually two projects now in my solution, and you can’t execute a library, correct? So what we need to do is right click on the client project and select Set as Startup Project. It’s going to close that, when we attempt to run the application. It’ll work. Furthermore, if we were to make any changes to how the library actually works, let’s say what could we do here? That’s interesting. Let’s do this. We’ll make a change in one spot and then I’ll go content plus equals THAT’S ALL FOLKS for the very end of that string this return. I’ll return content this time. Let’s make sure we have everything there. We’ve made pretty big change to the application. Now when I run the application, it will recompile the DLL. It will add it to our project and at the very end, it adds, “THAT’S ALL FOLKS”. The only thing I could think of off the top of my head. Hopefully now you can see that there are several different ways to add assemblies. If it’s part of the .NET Framework Class Library, then obviously there’s a way to do that. If it’s a free or open source, package that’s available from NuGet, we can use the NuGet package manager or we can create our own third party class library and then add a reference to it by browsing. Or if we were to create the client and the library inside of the same solution, then we can reference it in the add reference dialog. But just under the project solution option, and we get the added benefit of being able to make updates, not having to go through two copies of Visual Studio to updated. It’ll update the next time we hit, run it or recompile it and everything. That’s pretty much it for this lesson. We’ll continue on the next lesson. Will see you there. Thanks. Hi, I’m Bob Tabor with Developer University for more my training videos for beginners, please visit me at devu.com. Previously, we looked at arrays which allowed us to keep a sequence or group of related data together inside of the same variable, so we would create an array by providing a data type, and so each item in the array had to be of that data type. We would also provide the number of elements we expected in the array by defining that number between a set of square brackets. Now that we have that predefined sized array, we could add items into each element of the array or retrieve values out of each of the elements of the array by indexing into the array using a zero based index to index in and address one specific element of the array. Now, once we have the data collected into an array, we could do some interesting things. We could iterate through the array and investigate each element in the array, or we could even pass the array around as if it were one variable. Pass it in, for example, as an input parameter to a method. But you recall that time, I also said that at some point we would talk about collections. I even gave collections a nickname, calling them arrays on steroids. I think you’re going to agree after this lesson that collections are great whenever you’re working with all data types, especially those custom data types that we’ve been working with up to this point in this series of lessons. For example, the car class that we created ourselves. Now, as far as the .NET Framework class library is concerned, it will often use both arrays and collections, depending on the need. But I think you will probably wind up preferring to use collections in your applications because of the rich filtering, sorting, and aggregation features that are available to collections through a technology, a language called LINQ L-I-N-Q, which stands for the language integrated query. It was a very innovative feature whenever it was first introduced back a number of years ago in C-sharp and other .NET languages. Other languages have since implemented something similar to it. But we’re going to dive into that topic of LINQ and what you can do with it in the very next lesson. But first of all, let’s talk about collections. We’re going to talk about two collections, specifically lists and dictionaries. Now, truth be told, there’s probably a dozen additional varieties of collections that you could use for very specific purposes. They each have a superpower. They each have a very specific use case where they’re intended to be used. I find myself using lists and dictionaries 95 percent of the time. So we’re going to focus on those for this lesson. But after this lesson, by all means, feel free to go off and learn all of the additional collections that are available to you and what they can do that’s a little bit different than the list in the dictionary. Suppose that I have a number of cars on my car lot and I want to write an application that allows me to manage them. So I need some way to collect all of the individual instances of the car class together into a single array or collection. Now again, I might use an array of cars, but I think I’m probably going to choose to use a collection because of the added features that I’m going to gain using collections. We’re going to talk about a bunch of different types of collections, but I want to start off with a conversation about an older style of collection that’s no longer used anymore to show why there’s a newer style collection that’s available, and it’ll help you maybe understand that idea a little bit better. As you can see, I’ve got a project called Working With Collections already set up here. Please take a moment and create a new console window project. I’m also going to paste in two classes that I’ve defined simplified version of the car class that we’ve used before. Then also, I’m going to create a book class, as you can see there at the bottom. Very simple classes. The next thing that I’m going to do is actually paste in some code to actually create new instances of each of these classes and then populate their values. You may want to pause the video yet a third time and copy in the code that I have copied to screen there as well. The very first thing that I’m going to want to do is to work with a collection and I’m going to work with something called an array list. Let me just say this about array lists that they are dynamically sized, which is one of the great benefits. You don’t have to do anything to say, I need to add one more item and another item and another item. Remember with arrays, I said it was possible to resize an array, but it’s a little bit of an advanced operation. Not so with an array list. That’s one of the big benefits. You can just keep adding items to it and it’ll be just fine. It will also support cool features like sorting. You can easily remove items from the collection and so on. Let’s go ahead and create a new instance of this array list. When I do notice that we don’t already have a reference or a using statement to a namespace, so what I’ll have to do is hit Control period on my keyboard, and you can see that it is in a namespace called using system. collections. I’ll go ahead and add that namespace to my project and so will create a new one called myArrayList equals new ArrayList, like so. Now that I have my array list, I can begin to add items to the array lists like, for example, the first car, and then I can add a second car like so. Now, one of the problems with the old style collections like the array list is that there was no easy way to actually limit the type of data that would be stored inside of the array. For example, I want to work with automobiles, but I might accidentally add a book into the array and it will work just fine. There’s no complaints. The old style collections are not strongly tight in so much that you can put anything inside of a collection. At first glance, that might seem great. But what if I wanted to actually then print out a list of all of the cars makes and models? Let me start by at the very bottom here type Console.ReadLine so we can get through that formality and then I’m going to just do a for each. What am I going to work with here? Let’s just say I’m going to work for each car car in my array list. Then I might do a Console.Writeline, and let’s just go car.Make like so, and print that to screen. You must run the application, and we will get an exception whenever we hit the third item in our array list. Notice that it is printed first to the screen, but when we get to the book, it says that there’s an invalid cast exception. In other words, we could not convert a book which was the third item in the array list into a car, so when we get to this spot as we’re iterating through each of the items in our array list, we’re going to hit a problem here. The fundamental problem is that we allowed our collection to store something other than cars, so we cannot work with these collections in a strongly type fashion. Now, what I can do, one of the neat features here, is that I can actually remove that item prior to going into that for each list, and we should just be able to execute the application without problem. That is at least one of the good benefits there. But unfortunately, the downsides outweigh the benefits. Let’s go ahead and take a look at the newer style collections. The first, I said, was that we were going to look at a list, and more correctly, we’re going to look at something called a generic list. Often, you’ll see it referred to as List of T, like so. That of T in the term generic might require a little bit of explanation. When done, that was first released, the first set of collections allow you to put anything you wanted into them, like we saw here just a moment ago. Now, it might make sense in some contexts, but typically, it doesn’t, and it leads to potential errors like you saw. Now, at some point, then, C# introduced the notion of generics, and specifically for our purposes, they released a series of generic collections. A collection is essentially generic but it requires that you make it specific by giving it the data type that should be allowed inside of that collection. We have a generic list but we’re going to make it a specific list to car so that we can’t even add a book to that collection. Let’s attempt to do this one more time. This time we’re going to go List, and notice that I’m using angle brackets, and in-between the angle brackets, I’m going to say what data type I want to use. In this case, I want to use the car data type. List of car called myList equals new List of Car, like so. At this point, we can go ahead and add the car1, just fine. We can add car list to myList beginning at car2, just fine. But what happens when we attempt to add the book into our list? Well, at the point when we attempt to add the book to the list, we get an exception. We hover over and it says it cannot convert a book to a car. That makes a little bit more sense. It is specific to a car data type, so we cannot add a book to that list. But from this point on, we can work with it now with some confidence, so each car car in myList, and we can use the car.Model, like so, and we would get what we would expect here, create a list of our car models. That’s one of the big benefits of working with a generic type, is that it allows us to work with the specific data type and only allow those types into our collection. This is probably the most popular of all of the collections available. But I’m going to show you one additional collection called the dictionary. A dictionary is similar to, think of Webster’s dictionary, where you have a word and you look it up in alphabetical order and find the word that you want definition of. Then once you find the word, you can look to its right and it will have the definition. There is a key, which is the word itself that we want to look up, and then there is the definition next to it. There are two components to each entry in a dictionary; there’s the key and then the value itself. Typically, when you see a generic dictionary mentioned, it’s going to be listed like this Dictionary of TKey, TValue. In this case, what we’ll do is specify the data type of the key. This allows us to find one specific item by the key. Now the key should be something that is unique to every entry in the dictionary. In the case of people, there might be some identifier. It could be a customer ID in your system, it could be a Social Security number if you’re in the United States, but something that uniquely identifies one entity inside of that dictionary. Then the value can be of any data type. In the case of, again, a customer, you might have the customer ID being the key, but the customer object itself is the value that we actually want to get access to. Now, in our case, this seems a little bit weak because our car class only has make and model, and we know that we can have multiple cars that have the exact same make and model. They may have different colors, they might have been created in different years, but you can have multiple cars in the car lot that have the exact same make and model. Neither of these are good candidates for keys, but there is something called a vehicle identification number. Let’s do a prop string and let’s call this VIN. That will differentiate every car in the world that’s been created. What I’ll do is come back up here to the definition in the car1.VIN and I’m just going to use a very short VIN number. I think they are typically like 18 or 24 characters long, something like that; I’m not exactly sure. But this should uniquely identify every car in the world, especially every car in our car lot. Now what I can do is create a dictionary of my cars by starting off and saying something like dictionary, and they were going to give you the two data types. The VIN will be of type string, and then the actual value will be of type car. We’re going to call this myDictionary equals new Dictionary of String Car; notice the InteliSense help me out by essentially giving me a lot of that, and I can just hit the semicolon at the end of the line for it to type out that entire phrase. Now that I have this, what I can do is go myDictionary.Add, and we’ll do car1.VIN and passing car as the actual value. The car1.VIN, again, is our key into the actual car1 itself. Likewise, we’ll go add car2.VIN in car2. At this point, here, if I were to attempt to find a given item, so Console.Writeline, and I need to find a specific car in my car lot, I can allow a user to type in the VIN number and I can look it up in the dictionary quite easily. Then there’s a number of different ways to go about this, I think probably one of the easiest ways actually. Let’s go back and not use the dot. Here, I’m actually going to use the key itself, so we’ll call this B2. Then now we can reference a specific item in the Dictionary of Type car so we can get the make, for example, and print that out to screen, like so. We were able to find the Geo that way. Hopefully that makes sense. Let’s continue on, if you recall when we originally were looking at, let me comment all this out. We were looking at a raise, I said there’s some interesting things you can do to initialize an array with values like we see here. We’re creating an array of strings called names and to initialize it, I give it a collection of names that are common to limited. Now I have an array that has four elements in it and it’s already been initialized with the values. You can do the same thing with the objects to initialize objects at the point of instantiation, to do that will use an object initialization syntax. In fact, let’s go ahead and just approve this all works is coming out everything we have up here as well and get rid of the cars in the book, we’ll come down here and go car1 equals your car and then notice what I do, I use that same syntax the curly braces and inside of here, what I can do is actually define all the values to make equals. Let’s just dream large here and go make in the model would be a 750 and we’ll make it an ally and then we’ll also give it a vehicle information of C3 like so. Now I’ve done the actually three things in one line of code, I create a new variable called car I create a new instance of car and computer’s memory now I’m getting access to that address in memory by using the car1 label, the variable name and then I go ahead and populate the properties of the car object at the moment that I create that new instance by using this object initializer syntax. Some people don’t like this. It looks like it might be doing too much in one line of code, but I think you’ll find that if you ever do need a hard code, examples like I do frequently that the shortened syntax actually saves you several lines of code and it’s just fine it’s valid code Let’s go ahead and while we’re working here, let’s go ahead and create a Toyota. We’ll set the model equal to a 4Runner and we’ll get to that a VIN of D4. Like so and now we can work with the cars just like we did before but in and of itself, this might not be so interesting but this is the object initializer syntax. We can take this one step further when it comes to working with collections, we can use collection initializer syntax. I want to point out one other thing that we didn’t have to use a constructor to make this work like we looked at before that we’re able to regardless of the constructor, go ahead and set these attributes just like we use the syntax there. Well, let’s now talk about a collection of initializer which can look a little hairy, but it’s essentially the same thing we’re just taking it to the next level here. In this particular case, let’s go ahead and create a list of car called my list equals a new list of car. Now, at this point, what I can do and notice that I put this on separate lines here, I typically might keep this on the same line just for my own sanity here and now inside of this new empty list of cars, I can create a series of car objects like so. In fact, what I can do at this point then is use an object initializer inside of that, so here we’re going to make vehicles lose it all then we’ll set down the model equal to Cutlass Supreme and then the number of a set that equal to E5, so comma and then we’ll create another new car to add to this list of cars and we’ll set its object initializer setting it’s make equal to Nissan and its model equal to an Altima then finally, it’s VIN will equal F6, something like that. Now what I’ve done, all in one line of code essentially is I’ve created a collection and I’ve added two objects and in each of those objects, I went ahead and already initialized all of the property values. There’s a lot going on there and just that one line of code. Great. At any rate, just wanted to recap the things that we talked about in this lesson. First of all, we talked about the difference between arrays and collections and I promised that there will be a more obvious set of features that are available to collections, which we’ll learn about in the next video. We talked about the old style collections versus the new generic collections. We said generic collections are superior because they allow us to make sure that we’re only adding specific types to our collections so we make a generic collection specific by passing in the data type that should be allowed to be referenced inside of that collection. Then we looked at object initializer just a shorthand syntax for initializing the properties of a new instance of an object and then finally taking that one step further within a collection initializer where not only are we creating a new collection, but then initializing it with new instances of the car collection. In both of those cases then we are using object initializers. We can do it all on one line of code. Now, honestly, unless you’re building a lot of example code like I do, you may not see this as often unless you are creating some hardcoded objects for use within your application. But I wanted you to be aware of that syntax nonetheless, because we’re going to use it again in the next lesson and we’ll see you there. Thank you. Hi, I’m Bob Tabor with Developer University for more my training videos for beginners, please visit me at DEVU.com. In this lesson, we’re going to look at link the language integrated query syntax that was introduced some years ago to provide a way to filter thoughts and perform other aggregate operations on collections of our data types so will demonstrate two different styles of Links Syntax there’s a query syntax that will resemble the structured Prairie Language sequel for querying databases. If you’re already familiar with sequel, this will at least feel familiar. Then there’s also a method syntax which might feel more familiar to C-sharp developers. However, there is one little strange nomenclature thingy that we got to figure out but I think it’s pretty easy. I think I have a good way of explaining it to you and hopefully you’ll understand what it’s trying to do there but what I’d recommend is you find the code for this lesson there should be a before and after folder and you want to copy the code in the before folder in your project’s directory and then open it up and you’ll be where I’m at right now. In the understanding on project, you can see that I merely created a car class and then I also have here a collection initialized class filled with cars filled with attributes that will be able to search and sold on and that’ll give us something to work with here. What I want to do to begin with is to show you a comparison between links query syntax then links method syntax to do the exact same thing. You’ll see the obvious difference and we’ll talk about the ways in which they’re different but let’s begin with a query where we want to find all BMW in this list of cars called my cars. It’s as easy as this, and we’ll talk about the VAR keyword here in just a moment but BMW equals from car any cars looks from car in my cars, where car.Make is equal to a BMW, that’s car. Now, let’s come down here and print all those guys out. Let’s go console that right line and let’s provide the vehicle information number let’s do zero on on, actually, let’s do this. It’s good for each tab VAR car in my in the BWS Console.WriteLine and then we’ll go car.Model and car.VIN. Let’s go ahead and add some of our replacement characters in there. Now, let’s go ahead and run the application and we see that we get three cars that have been returned, so of all the cars, I think there’s five or six three of them with those VINS A1C3 and E5 are BMWs. If you take a look at the data, that would be correct. Very quick, concise way of finding only those cars that match that criteria. What if we wanted to add additional criteria? Say, for example, we wanted to also see where the cars year equals 2010. We could do that and rerun the application and now we see that it just finds one of the BMW cars was created in 2010. It is this last one, the 555i. That is the language integrated query syntax, the query syntax of Link. Let’s go ahead and comment that out and compare that to the method syntax and so here will go far. BMW equals myCars.where. This will give us all the BMWs, so let’s go and run that. It gives us the same three that we got before. Now, what if we wanted to also find only those where the year is equal to 2010? We would do that. You can see we found just that E5; that last one. This might take a little explanation here. For the moment, let’s just ignore this last part, we’ll talk about that in a moment. But what you see here, in fact, the whole thing in between the opening and closing parentheses is called a Lambda expression, and you can think of it as a mini method. Essentially, what will happen is, you say given p, so given an instance of the collection, only return back to me those instances of car where the make is equal to BMW. See how easy that is? Again, just a mini method. You could think of this as like the input parameter, and then this is just some condition. When it’s true, then return that instance and add it into this little collection over here, so now that we have a subset of all of the available cars in our car lot. Furthermore, I just added the logical and operator and said, and make sure also that it was in 2010. Well, that filters out two of them. Again, a Lambda expressions are just many methods, so for any given item in the collection it has to match that criteria. If it does then we can add it to this little subset collection over here that I’m calling bmws. The var keyword it has a very different connotation in C# than it does in other programming languages. Here I would ask that you forget what you know about var from maybe JavaScript or Visual Basic or some other programming language, it does not mean the same thing. In this case, the var keyword says that we’re going to let the compiler figure out what the correct data type is. I’m not even sure what gets returned from this little query that we do here. If you were to hover your mouse cursor over the where, you can see that it’s going to return back in i numerable car. What’s that? Not entirely sure, doesn’t really matter. I don’t care what it is, I know that it is a collection of cars. To prove this point we’ll talk about this in just a moment a little bit later where the var keyword can really come in handy because we truly don’t know what it is that’s being created by our link queries. Again, the var keyword it’s still strongly typed. We’re just going to let the compiler figure out what the type is at the point when the code is compiled. Let’s move on, and let’s take a look at a few other examples. I may want to find an ordered list of cars, so I might go orderedCars equals from the car in m Cars, order by car.Year descending, select car. That’s how I would take all of my cars and order them in descending order by their year. Let’s just change this from bmw, let’s put this to orderedCars like so, and this might help if we actually saw the year itself so I’ll add in the car.Year as well. Let’s go ahead and run the application. You can see it starts at 2010 and in descending order, works its way back to 2008. Awesome. That same query if we were to do it in using the methods syntax instead of the query syntax, it would look something like this. var orderedCars equals myCars.OrderByDescending. Given each item in the collection only return those or actually order them by the year like so. We should see the same grouping and we do. Starts at 2010 and works its way back to 2008. Again, in my opinion, this is more concise. The only conceptual hurdle you’ve got to jump over is just make sure you understand what a Lambda expression is. In this particular case, it’s not a filter, we’re just saying, given each item in our collection, we want to order by this particular property; the year and then add that ordered item to our new collection of cars over here. Now, there’s a lot of interesting things that we can do, and I’m only going to work with the methods syntax from this point on. The first we might do something like this, for example, if we want to find just the first item, so let’s go ahead and grab this and maybe we want to find the first item where the make is equal to a BMW like so. This will give us the first car; the first BMW car in the list that it finds. Let’s go ahead and console. In fact, let’s change the name of this to firstBMW, so Console.WriteLine. All that right. firstBMW. just a VIN number should be sufficient. Let’s run that. We can find that the first BMW in the list was A1, or we can do the first BMW, and we can actually start by ordering by descending given the year. You can see I’m chaining these together, we’ve talked about method chaining before. This will return a collection of cars and then this will return a single car in that collection. Then we’ll print that single items then out to window, in this case E5. The list is first sorted and then we grab the first one that matches our criteria of BMW. That’s how we can use first. We’re going to comment that out. We can also do something like this, Console.WriteLine., and inside of here, let’s go, myCars.TrueForAll and say the year is greater than 2012. We need one more right there. Is it true that all the cars in my car lot that every one of them is greater than 2012? That would be false. Well, then how about are they all greater than at least 2009? That’s still false because we have at least one that was created in 2008. If we were to change this to 2007. Are they all at least greater than 2007? True, so that’s true for all. Very helpful in order to aggregate and look across all of them and see is this true for all the items in my list. We can also even do something interesting like this instead of doing this for each statement where it’s essentially what, at least two if not four lines of code we can create a for each like so. myCars.ForEach and then inside of here for every item, let’s just do a Console.WriteLine and in here, I can do p.VIN and p.StickerPrice. Let’s go ahead and do that. In fact, we’ll just do that as well, one and zero. Hopefully, that all makes sense. Now let’s run that and see what happens. Here we are, we’re able to list them all out and format their values, so you see how much more compact this looks than what we were writing here. We do it all in one line of code. Again, we’re passing in for every single item in our collection just call Console.WriteLine and then use that particular item’s VIN sticker price inside of our formatted string. Here’s another interesting example of this. Maybe in each case we want to go, so myCars.ForEach. In fact, here let’s do this before that line of code. Let’s keep that one and then go myCars.ForEach. In this case, I want to perform an operation on each of the data inside of there, so I might take the sticker price and reduce it by $3,000, actually let’s go minus equal to. This will take the sticker price and subtract $3,000 from the sticker price of every car in my collection. You can see now what was if we could get a comparison going here. See, unfortunately not going to be very easy to do, but you can see that what was $55,000 is now 52,000 what was 35 is now 32,000, and so on. Again, a lot of functionality in a very small space. Let’s continue on with this thought and go and do something like, myCars.Exist. Do we have a car in our car lot where the model is equal to the 745LI, true or false. Here let’s do a Console.WriteLine and let’s see if they turn true or false? Yes, we have at least one item in our inventory where the model is equal to 740LI. Now here’s another good aggregate function. Here, let’s just do Console.WriteLine, and let’s go, myCars.Sum, and here we’ll say, sum up all the sticker prices. Let’s see what the total value of our car lot is right now. You can see that it’s about 247,000 so actually, there should probably be a better way to format that using a format code but hopefully you get the idea. We’re able to sum up a single field across all objects in our collection of cars. There’s so many other things that I can show you, but I don’t want to overwhelm you, but I want us just to go in one ear and out the other for now. This VAR keyword we’ve looked at, and I said that we use it because we want the compiler to figure out what the data type is. Sometimes it’s easy for us to figure out what the data type of something is. Sometimes it’s not so easy. To illustrate this, let’s do a Console.WriteLine line and what I want to do is call on myCars, I’m going to call the get type. In fact, all data types in.Net have this GetType method declared because it’s declared on the grandparent of all objects called System.Object. It defines this method called GetType, which will tell us what the type of a given object is and we can print it to screen. In this first case, what is myCars? Well, myCars is a generic list of the car data types so this understanding link is the name-space and specifically, though, it’s the car type. We’re basically saying this is a list of T, a list of car. That’s what’s being printed out whenever we’re looking at what the cars are, and that’s pretty easy to see because we define it here. But once we perform an operation like one of these here, let’s just see ordered cars and copy that again and stick it down here, and then I’m going to do Console.WriteLine, orderedCars.GetType and it’ll show us what the data type is for ordered cars. Let’s go ahead and compare the two. Now, in this case, you can see that we’re no longer dealing with a list of car, even though under the hood we know we’re working with a list of cars the way that it’s represented in.Net is that it’s actually ordered enumerable so an ordered list of the LINQ.Car, Understanding LINQ.Car. Again, that makes sense. That’s an ordered version of cars. How about just a regular old where statement. Let’s do that. Let’s copy that and see what the data type of that is and then do the same thing here. Let us see what that is. Let us go and run the application again. Here is this third one. The second one was an ordered enumerable, then the one where we just called the where was an enumerable plus the WhereListIterator. So things are starting to get a little funky here. It might be difficult for us to be able to express this ourselves if it were not for this var keyword. The var keyword is essential to help us to be able to create these very complex queries, and not have to worry about what the data type of it is that’s returned. We know that it is a type of list. It is an innumerable list, whether it is ordered or not, and we can follow each our way through it or whatever the case might be. Now the last thing that I want to demonstrate, is I am going to take this first query here, and I am going to pop it all the way the bottom. If this stuff doesn’t make sense, don’t worry about it too much. I wanted to go in one ear and out the other, just to explain again the value of the var keyword. In this case, let’s change something about this. Let’s call this my new cars. Here, I am not going to return cars. I am actually going to do what’s called a projection. I am going to only take certain values, certain properties of a car, and I am going to project them into a new data type. What’s the name of the new data type? Where am I defining that data type? I’m not going to define the data type. It is an anonymous type. What’s the name? I have no idea, it is anonymous. We can define types at runtime and only choose those properties that we need in the type for the moment. Why may not be obvious just yet, but I want you to understand that there is this idea, what we can do here. In this case, let’s pull out just a few things like the car.Make, car.Model. That is all we want. We are going to leave all the other attributes of car alone. We are going to only take these two values, put them into a new anonymous type. Where is the type defined? Nowhere, we just made it up off the top of our heads, and we are going to save each of those anonymous types into a new collection of anonymous types. Let’s go. Console.WriteLine, and then take a look at newCars.GetType, and let’s run the application yet another time. This time you can see that we also here have an innumerable plus where select list iterator, whatever that means, but then notice that the data type involves something called an anonymous type that has two attributes, two string attributes, which would be the make and the model. I say all that to say this, that whenever you’re working with LINQ, there is a lot going on under the hood to make it all very easy and accessible, but it all depends on defining your types as var, which says, let the compiler figure out what the type is, we are not so worried about it, because the data type might be so crazy that we can’t even comprehend what it is. Hopefully that makes sense. Just to recap the things that we talked about, we talked about the difference between the query syntax and the method syntax. We looked at a number of different examples of the various LINQ extension methods that were available. We saw how we could break apart an individual Lambda expression, to better understand that essentially we are saying each item in the collection, run this little mini method against it, and return back a given item that matches that criteria. Then we looked at how to tell what the types were and what the value of the var keyword is, and then we looked at anonymous types. We covered a lot of ground, I didn’t explain everything in great detail. But the key here is just to look at that little

    formula and try to understand what it means. Look for examples online, make yourself a little cheat sheet, and you should be able to utilize these methods inside your own application. That wraps up LINQ. This will be the hardest thing that you have to think about today, I guarantee it. That is it, we’ll see YOU in the next lesson. Thanks. I am Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at DevYou.com. In this lesson, we will introduce a new decision statement, the if, else if else statement, and the conditional operator are both great. They work best when there is only a handful of things to evaluate. But if you start needing to evaluate many different potential cases, you might find that the Switch statement is a little bit more concise and keeps things a little tidier. That would probably be one of the only reasons why you would use it, and I will show you a second reason why in this video as well. We will come back to the switch in just a little bit. But first, I want to talk about a special data type called an enum or an enumeration. Typically, we want to limit the possible values of a given variable. Now, admittedly, we’re already limiting the possible values that can go into a variable by virtue of the fact that we’ve given it a specific data type. However, even within that, I may want to limit the number of possible values to just a handful. Typically in software development, you want to limit and constrain your data to ensure its validity inside of your system. An enumeration is a data type that limits and constrains all possible values to only those that are valid and have meaning within our system. For example, we might want to keep track of series of to-do items. Maybe that is the type of application we’re building, and each to-do item is represented by an instance of a to- do class. We may want to keep track of the current status of a given to-do item on our list. We may want to constrain the possible statuses to maybe like five, that the task has not been started yet, or it is in progress, or it is on hold, it is been completed, or perhaps it is been deleted. There might be some other statuses, but you can see how I may want to just limit the number of options that are available for a status field or status property of my to-do class. We could do this in a number of different ways. We could just concoct a numbering scheme, where one always represents not started, and two represents in progress. I refer to those as magic numbers. They may have some meaning in the system but it’s not readily obvious if you’re reading the source code. As the developer, you may have to look up at some external reference, maybe some code comments, and who knows, maybe they are not even current anymore. Maybe things have changed since whoever wrote those code comments originally wrote them. I may need to reference or look through a number of different code to ensure that what number one means in the system, what number two means in the system and so on. The same thing can be true with strings. I could just use a literal string to indicate the current status, so I could use a literal string, not started or in progress. But the problem with literal strings is that somebody can misstype them, or there could be a space, and not started one time, and then somebody uses not started without a space the other time. If you are looking for all those items that have not been started yet you may have a hard time finding those that have not yet been started or in progress because they are not spelled correctly or whatever the case might be. The great thing about an enumeration is that it gives us a textual equivalent to a numeric value so that it will remove any ambiguity inside of the system. As developers, we know exactly what we are working with, and yet behind the scenes, it is still working with the number. Enumerations are used frequently in the.Net Framework Class library for the very same reasons. For example, you can see here that I have a project, EnumsAndSwitch, and here again, if you look in the code folder for this lesson, there should be a before and after. You want to copy the project from the before folder and copy it into your project’s directory so that you can catch up to me where I am at at this moment. You can always pause the video and type all this in if you like, it can quite a bit of typing though. You can see that in this project, I have already created a to-do class, with a description of each to-do item, the estimated number of hours it should take to complete the to-do item. Then notice that I have a status of type status. Where does this come from? You can see directly below, I have created an enumeration called status, and I have not started in progress, on hold, completed, and deleted. Did you notice as I hover my mouse cursor over it, that each of these values are given a numeric values? Not started equals zero, in progress equals one, on hold equals two and so on. If we were to store these values somehow in a database or a text file, those are the values that might actually get stored. However, they will be translated into this more textual format so that when we are actually working with the data, as you can see here in the static void main as we are creating a new list of to-do’s using the collection, initializer or syntax, here, I am setting the status equal to either completed or in progress or deleted or not started and so on. Visually, it’s much easier for a developer to work with those options in a more textual way. Now, the.NET Framework Class Library will use enumerations extensively. In fact, even in the Console window, if we were to set the foreground color, notice that IntelliSense automatically pops up to the console color enumeration. See, it says enum over there. Let’s see. I don’t think you can see that. Let’s go up a little bit here. All right there. Now, you can see the word enum right here. It’s a console color in enumeration. When I hit the member access operator, the period, it will show me all the colors that we can choose for the foreground color of our console window, so I might choose dark red. Again, enumerations are great because they are descriptive and they limit the number of possible values for our applications, for the properties of our classes. The next thing I want to talk about is the switch statement, and these two are going to marry together here in just a moment. But a simple switch statement is going to look something like this. In fact, I’m just going to go switch Tab Tab, and that will create essentially the outline for it. In this case, we can use an individual to do item and choose it’s, or let’s say estimated hours. If the estimated hours are, for example, case four, then we might perform some operation until we hit the break statement. Or we could go case five, so we could perform something and then we would hit the break statement and break out. There’s also a default case, that would be the catch all just like the else statement and the if else, if else, construct. But the most important aspect of this, is the construct of the switch statement. You have the keyword switch, then you have a variable that’s under evaluation and then a series of cases where we would try to match it up with one of these cases, and then we use the colon after that case. We write our code below it and then we use a break statement to break out and continue on our execution of the code. Now we might choose to, for example, do something like this. This makes a little bit more sense to work with the statuses. In this case, we might go status.completed. We might do something versus case studies.deleted and we might perform some operation there and so on. Now the beauty of the switch statement and the enumerations are that they can conspire together here. Watch what I do. I’m going to type Switch Tab, Tab and then I’m going to do, which is each the items in the to do collection dot status, and then I hit the “Enter” on my keyboard twice. The second time I hit “Enter”, see the macro that will actually blow out, each of the individual statuses so that I can write code associated with each status. Isn’t that crazy? Now, I can do here anything that my business logic would require. I have an idea though. Let’s use the foreground color and change it up for each of the individual to do items. It can be as simple as this. Let’s just copy this, and we’ll put it here for each of these statuses. Then here at the very end, we will actually then do a console.write line of the actual item itself, the todo.description and here will change up the color. If it’s not started we’ll leave it as dark red, if it’s in progress, we’ll use green. If it’s on hold, maybe we’ll use the dark red. Let’s use the red here in the dark red there. Completed, let’s mark those as blue and if it’s been deleted, we’ll mark that with yellow. Now let’s go ahead and save and run our application. You can see we have a very colorful list of tasks that are color coded by their current status. See how cool that is. In this lesson, we talked about enumerations and why we would use an enumeration to constrain the possible values for a given property of our classes. We saw how it was used in the.NET Framework class library, one little instance of it here, where they’ve created their own enumerations. Just be aware of as you’re trying to work with a given class and its properties, always look at, for example, in this case, what data type it is. This is a data type console color and typically IntelliSense will point you in the right direction. As you hit the equal sign it will pop down to that data type, that enumeration so that you just hit the period then you can make your selections there. That’s a really good hint. Then we looked at the structure of the switch statement, where we’re evaluating something in between the opening and closing parentheses. We looked at the body, the opening, and closing curly braces, the entire body of the switch statement. Then inside the creation of the number of cases, each case equating to one possible value of the item that’s being evaluated and then a colon and after that, then any of the code that we want to write, and finally, a break line which will pop us out of that switch statements body. Then finally, we saw that there is a catch all the default colon, which we can use to write any code for cases that we haven’t accounted for in any of the other previous cases. That wraps up this lesson. Doing great work, getting close to the end now. You feel pretty confident C-Sharp. You’ve got the majority of it under your belt. Just a few more topics we want to cover, and then we’ll wrap this up. We’ll see in the next lesson. Thank you. Hi. I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. In this lesson, we’re going to talk about handling exceptions that occur within our applications. We’ll discuss what can go wrong, why things go wrong, and how to build resilient applications that are impervious to crashing through the use of C-Sharp’s Try Catch block statement. When the compiler catches a data type mismatch or an unresolved reference to a class or some malformed C-Sharp instructions, it’ll refuse to compile your C-Sharp code into a.NET Assembly until you fix the problem. These type of errors are called compilation errors, and that’s not what we’re talking about in this lesson. However, there are other types of errors that happen during runtime or in other words, they happen when the compile.NET Assembly is actually in the act of executing. Honestly, there are countless number of reasons why you could encounter an exception while the application is running, depending on the kinds of things you’re trying to do in your application. Many times these things are outside of the direct control of the software developer. For example, if your application can’t read or write to disk because a folder or a file is missing on disk where it expected to see it, it could trigger a runtime exception. Or maybe the files corrupt, or maybe the network access to that resource is unavailable, or it attempted perhaps to access a database, and it couldn’t find something in the database that it needed. A table, a column, whatever the case might be, because the structure has changed of the database out from under the application. All of these things and many more could cause the absolute failure of your application, and the user will see a nasty error message at runtime and the frustration, say the developer. In some cases, the developer may have not even foreseen that that could have potentially been an issue. If they didn’t see that it could be an issue, they couldn’t have accounted for it. Maybe the developer for example, allows the users to type in a country, but the user misspells the country name. Now, maybe they did that intentionally or unintentionally. Perhaps they maliciously use numerical characters instead of alpha characters. But as a software developer, your job is to make sure that you account for all of these possibilities. A friend of mine was fond of saying that 80 percent of all code exists to solve 20 percent of all the potential problems that could happen in your application. Generally, software developers should be pessimistic regarding the reliability of everything outside of their control. Whether that be input from an end user, any connection to a network, to the file system, anything that the developer cannot directly control be should be held a great suspicion. Again, if you rely on a file or a network resource, you should treat it with great suspicion. If you rely on the user to type data into your application, definitely treat that with great suspicion. It’s absolutely evil. This is the software developers equivalent to driving defensively. Always code defensively, which means you are always looking for problems all around you-all the time. Now, the way that the C-Sharp developer codes defensively, or one of the ways in which they do it is through the use of a try catch block, and I’ll demonstrate that in this lesson. Up to this point, we’ve been reading or actually writing files to disk. This time I want to read a file to disk. We use the same file class like we’ve used previously. I noticed that I already have a using stand for system that I also finds it. This time I want to use the read all text instead of the write all text. Here, let’s just go ahead and set this example. Notice that I’ve already got a project created called handling exceptions. Please, pause the video and catch up with me if you like. But here we go. String content equals file.read all text. Then let’s just for the sake of argument, hard code a location. I’ll put this at less than 22 slash example.txt and then we’ll do console.writeline.content. Then finally, console.readline like so. Great. So far, so good. Now, here I just want to demonstrate that this actually will work. You can see that I created of my route a Lesson 22 folder with example.txt in it. Let’s go and run the application and show that there is actually text in that file. It’s just a quote from Mark Twain. Now that we’ve got it working correctly, let’s break the application by giving it a fake name just by removing the E on the end of example.txt, and now you can see that we get an exception. This is a file not found exception was unhandled. I’ll tell you what, let’s do this. Let’s stop the application. That’s what the developer will see while they’re debugging their application if they were to run across this issue while they’re building the application. But what if we were to build a release version of the application by changing the solution configuration and then selecting “Build Solution”? Now we’re going to go out to our projects directory and I’m going to act like an end-user and actually attempt to use this application outside a visual studio, so outside of the debugging environment, just to see what the end-user would see if they ran into this exception at runtime. The name of this is handling exceptions, there you go. Let’s go into the bin directory, into the release folder, and then I’m going to double click the “HandlingExceptions”. Whoops. Notice that I get this ugly little message here and it’s trying to help me figure out what happened and I get all of this text here with all this ugly information just spewing out all this information that an end-user probably would have absolutely no idea what the issue was. Although we can read here near the very top that the problem is that it couldn’t find the file Lesson 22 slash example with no E dot txt. Now, a very observant user might be able to look at this and figure it out if he stared at it for a while. But most users are going to be scared off by this, and I don’t blame them. We ideally would like to make sure that the end-user never sees anything like that whenever they run our application. Again, Windows will then close the application, notify you if there is a solution available. There’s just a mess going on there, and we want to protect our end-users from this mess, from ever seeing this. What we can do is actually wrap a try and a catch around this. We’ll do this. There’s a couple of different ways to go about it. I’m just going to take the easiest approach to begin with. What I might do is just go ahead and let’s switch back to the debug configuration and run the application. Now, you may have noticed that the application ran briefly and then went away, and the reason it did was because we ran this, we hid an exception here, the catch statement kicked in, there’s nothing defined in the catch statement, and we continued on. What if we were to move this to right there? We would at least see the application now run for a little bit and we would see no output. So still not an ideal situation, but at least we’re not seeing any exceptions. Let’s go one more step with this and let’s actually catch the exception that occurred. Here we’re going to catch an exception that we’re going to call ex. Now, exception is the most general type of exception that can be thrown. What we’re going to look at in a few moments are very specific versions of exceptions. But this is the most general version so that at least we can see what the problem is and we might do something like, there was a problem, something like that, and even we could provide a description of the problem, so the message from the exception. Let’s go and run the application. At least this time we’re giving the user some feedback here. There was a problem, could not find the file Lesson22/example.txt. That’s better. Again, it would require an observant and slightly more technical end-user to be able to resolve this issue on their own to say, “Wait a second. I wonder if that file might be named something different here on my own hard drive.” As they traverse through and look for the file, they’re, “I see what the problem is. There’s no e on the end of example.” That’s asking a lot of your end-user, but that at least is a step in the right direction, at least we’re giving them some clue as to what the issue is. Now, really what I would like to do is account for all the possibilities and be a little bit more specific. If I were to hover my mouse cursor over this read all text where the issue seems to be mostly, you’ll see that we’ve only been looking at the return value and the input parameters for a call to a method. But notice below that there’s a list of possible exceptions that could occur. Also, if we were to go to System.IO.File.ReadAllText. Let me just copy this and let’s go to Bing. We’re basically going to be searching through Bing here for System.IO.File.ReadAllText. That should help us find an article in MSDN that has a full description of this method. You’ll see that there’s two overloaded versions. We’re using this 1st overloaded version of it. Then if we were to scroll down and pass some of the initial information, there’s a list of exceptions, and it would provide us some scenarios why that particular exception might happen. Like a security exception, the caller doesn’t have the required permission. The path is an invalid format. Interesting. File not found, the file in the path was not found. There’s also a directory not found. Interesting. Maybe the path was too long or maybe we provided a no value. There’s a lot of things that could potentially go wrong whenever calling this method. As developers, we really need to, to the extent that we can, account for all those potential situations, at least the ones that make sense. For example, I could rewrite this code example to begin catching some of those specific examples. For example, let’s take a look here. Let’s, first of all, make sure that the directory exists, and then if it does exist, then we’ll check to make sure the file exists. Then if the file in the directory exists but we’re still getting exception, then maybe we let it drop off to this most generalized exception here. I’m going to start from the most specific case and then work my way to the most general case. In this case, I think the file not found exception is probably the most specific of the ones that we’re going to work with. Then we’ll catch the directory not found exception. Then if that doesn’t work, we’ll just print out whatever the exception was. Here I might do something like Console.WriteLine and say there was a problem. Then give it a specific. Make sure the name of the file is named correctly, should be example.txt Then we can do something similar here and say there was a problem. Make sure the directory:\Lesson 22 exists. It’s something like that. Remember, we’re getting the red squiggly, why? Well, because we either need to add another backslash here or add the @ there, remember that from earlier? Let’s go ahead and test our application. I’m going to set a breakpoint here whenever we hit this line of code so that we can watch this execute. Let’s go ahead and step over. Looks like it found the file not found exception, and so we will see, there was a problem. Make sure the name of the file is named correctly. Then let’s go out and let’s rename this to Lesson22a. I think we’re still going to get the same actually exceptions. I know we did get the directory not found exception, good. In this case, we’ll see that error message, make sure the directory Lesson22 exists. Then for any other exception, maybe there’s a permissions issue on the computer, maybe the file is corrupt somehow and we can’t read from it, we would get this last catchall, where we catch just the general exception and print it to the user. When you read the key to this is that we check the most specific exceptions first and the most general or generic exceptions last. There’s also one other item I want to add here, and that’s a finally statement. This is where we would write any codes to finalize, which might mean setting objects to null, closing database connections, but this code is going to run no matter what. We’re just going to go console.WriteLine, closing application now that like so that we can see that this code will run regardless. It’s just that one last chance as a developer to clean up our mess before we stop the execution of the application. You can see that now represented here by closing the application now. Great. Now, you might look at this and you might think to yourself, great, I’m going to use this try catch around everything in my application. Every single line of code in my application, I’m going to wrap it with a try catch. I’ll just take every method and I’m going to blindly just copy and paste everything in there. That’s definitely a strategy that some people take. It’s a little bit lazy, quite honestly. Some developers have done that, but they’re often ostracized by their end users for providing very cryptic error messages. If we were to leave all of these off and just wrap everything and just only show the exception ex, we would just be saying, hey, there was a problem here, figure it out for yourself. That’s not really advocating on part of the user. We’re not protecting the user. Furthermore, we might be tempted to provide some type of debugging information for ourselves as developers. Sometimes you’ll see some error codes pop up that no human couldn’t be expected to understand, except the guy who originally wrote the application. The reason developers do this because sometimes they take that exact approach where they just say, hey, we’re going to forget about the user. I’m just going to wrap everything in a try catch and it will pop the error message to me, it’ll flip back to me. I’ll fix the problem and everything will be okay. But, again, this catch all is convenient to the developer, but it’s really frustrating to the end user so you shouldn’t do that. You should strive to put the same amount of attention into protecting your user from having these issues and protect them from having to guess at what to do next by simply helping them fix the problem. Tell them specifically if you possibly can. If you the developer can fix the problem, or at least you can point the user in the right direction, then that’s awesome. You should do that. But if you can’t, well, then at least try to identify the exact nature of the problem and then ask the user for the type of input that you would need as the developer to fix the issue. You don’t want to leave your users feeling stupid that they did something wrong. You want them to feel empowered and you want them to feel like your application is well built and it considered them whenever you were building it. That’s what makes your application polished. It’s what users expect, a reliable experience with no surprises. To recap this lesson, we talked about a number of different things related to exceptions that can happen essentially any time that you the developer are not completely in control and you’re accessing things outside of your boundary of control, outside of your domain. You need to wrap those in a try catch and be thoughtful about the types of exceptions that you’ll be handling, listening for specific exceptions that you know a particular method could raise, and it’s easy to find out. All you got to do is hover your mouse cursor over it, or you go to mstn and you find that method and you look for it like we did, all the potential exceptions that could happen. Then be reasonable about it, but then write the code necessary to handle those exceptions and protect your end user. We looked at the try, the catch, we looked at catching the exception and then using certain properties of the exceptions, like the message property to print out to the user what the issue was. We could also use this to log the error, even send it to a centralized logging service like application insights that’s available from Microsoft Azure to report back to the developers what the issues were. Then you can use the finally code block to clean up any connections you have to file systems, databases. You can set objects equal to null and go ahead and remove all of your references and be very explicit about that before you shut down the application. Hopefully that was helpful. This is a great lesson in building resilient applications, giving the users the experience that they would expect whenever things go wrong in your apps. We’ll have one or two more lessons and then we’re done. We’ll see you in the next lesson. Thank you. Hi, I’m Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. In this final tutorial video, in this course, we’re going to discuss event-driven programming. Event-driven programming is really at the heart of Microsoft’s presentation APIs, whether it be for web or Windows. Really, for that matter, it’s at the heart of just about every other API in the .NET Framework Class Library. It is so essential that we have to spend a little bit of time here near the end talking about it because it’s that next step that will help you graduate on to building real applications with real user interfaces beyond this course. Events allow you, the developer, to respond by handling those key moments in the lifecycle of the application’s execution, allowing you to write code to respond to an event being raised. Up to this point, in our simple console window applications that we’ve been building, there’s really only been one event that ever gets fired off, and that is the application startup. On application startup, the static void Main is executed, so it’s handling that event, I guess you could say, and this is where we write the majority of our code, and that’s why it actually executes whenever we run the application. Now in a modern user interface, whether it be for Windows or for web, users can interact with the various elements that they see on their screen. They can hover their mouse cursor over given things, like buttons or graphics or text boxes, and they can see maybe a change in the visual presentation, maybe they see a pop up that explains the usage of that given item, perhaps they can click on an item to enact some business functionality inside the application, they can press keys on the keyboard to make things happen, they can type inside the text fields, or they can drag and drop items around the user interface, and each of those will raise a number of events. As a software developer, you can decide to write code that responds to those interactions between the end user and those various user interface elements on screen, and you can also choose to ignore those that really don’t make sense that you really don’t care about, you don’t implement for your application. A given component, let’s say a button, for example, in its development by Microsoft, they included or defined an event, let’s say it’s the click event for that button. Now the developer, you and I, we say, “Hey, I’m going to write a code that performs this business logic that I’m writing here in C# whenever that event, the buttons click event is raised, that I want this code that I write to be executed.” So the developer creates a method and attaches that method to the event, and I’ll show you how we do that in just a little bit here. As the application is running, the user is interacting with the application. Eventually, they click that button. The .NET Framework runtime says, “Okay, if you were listening for the button click event, here it is.” It just happened, and it will notify every one of the methods that you and I, as developers, have attached to that specific event notification, that we’ve registered to that event. Now I’m going to show how events are used in a simple Windows application near the end of this video in a more realistic scenario, but first, I want to start with the absolute basics and keep things as clean as possible, so we’re going to work purely in a console window application. We’re going to work with a timer class, a timer object, and it has one event which is Elapsed. We can say after a certain amount of time, we want you, timer object, to execute or to raise an Elapsed event, and then we’re going to attach our event handler code to that event so that it gets executed every time that event is raised. Maybe it’ll be easier to see this in action than explain it. There are a number of different timer classes inside at the.NET Framework Class Library. We want to make sure we get the right one. I want to work with System.Timers.Timer, and I don’t want to use that long name every single time, so I’m just going to add that to my using statements up here at the top like so, and I’m going to say “Timer myTimer equals new Timer”. One of the overloaded versions of the constructor for this timer class allows us to pass in the interval in milliseconds. So every, let’s say, 2000 milliseconds we want the Elapsed event to fire, to be raised. So 2000 milliseconds would be simply two seconds, which is an eternity as far as a computer is concerned. Next up, what we’re going to want to do is say, my Timer we know that it will raise an event called Elapsed, and so we want to create an event handler, a method that will be executed whenever the Elapsed event is raised by the.NET Framework runtime. Here, you can see that we get this little message on screen that says, “Press TAB to insert,” and I press “TAB”, and it automatically creates the method stub called MyTimer_Elapsed, and it creates in a very specific way with a very specific method signature, and it also gives us this little stubbed out, “Hey, don’t forget you did not implement me,” so throw new NotImplementedException. Let’s go ahead and remove that for the moment, but notice what happened here as well. We are attaching or registering an event called MyTimer_Elapsed to the Elapsed event, so this references this code block right here. Inside here, we can write the code that we want to execute each and every time the Elapsed event is triggered inside of our application. This is where I might write something like Console.WriteLine, and the Elapsed event will send along some event arguments. One of the interesting event arguments is actually the signal time, and that will give me the exact, down to the millisecond, when that particular event was raised. Here we go. Actually, let’s do it this way so that we can format it nicely. We’ll call this Elapsed, and then hour, minute, second.fff. That should give us down to milliseconds. Now what we’ll do is actually tell the timer to start ticking by calling the start method, and then we’re going to go Console.ReadLine, and we’re going to say, “Continue running until somebody hits the Enter key on the keyboard.” Hopefully that makes sense, and let’s run the application. Now we see every two seconds, we get this message. You can see at 32, 34 seconds, 36 seconds, 38 seconds plus some thousandth milliseconds there. We get that MyTimer_Elapsed method executing. Now let’s do this. Let’s say that we want more than one event handler to execute whenever the event is raised. I can do this all day long. I can say, “Hey, well, let’s go ahead and add another method.” This time it will be called MyTimer_Elapsed1. Notice the 1. I’m going to get rid of this little box again. Inside of this new method, I can do essentially the same thing, and I’ll just use that Elapsed1 versus Elapsed. In fact, just to make this obvious, I’m going to use that little trick we learned just a lesson or two ago, where we set the ForegroundColor equal to the ConsoleColor.Red. That would be for the second one, and then we’ll do Console.ForegroundColor equals ConsoleColor.White. We can see clearly the two different event handlers that are both executing whenever the Elapsed event is raised by our timer. Let’s run the application, and now we see the pair running every two seconds. We could continue adding additional event handlers to the event. That’s what this little operator is doing. It’s saying, “How many current items are subscribing or have been attached to this event, I want you to attach this other one too.” Now we can do the opposite as well. In fact, let’s go Console.WriteLine line, and we’ll say “Press enter to remove the red event.” There’s probably a better way to say that, but hopefully you get the idea. Then after this ReadLine, we’ll add another ReadLine for the very end of the application, and in between what we’ll do is actually unregister, detach this second event handler for this event, so we’ll just do the reverse. myTimer.Elapsed minus equals MyTimer_Elapsed1. So now we have removed it, and it should no longer execute whenever the Elapsed event is raised. Let’s run the application. You can see, here we go, and now I’m going to hit the Enter key on the keyboard, and we should only see the white, the first version of our event handler firing every two seconds. Hopefully, that all makes sense. This is the most simple scenario that I could think up without having to actually create a real application, and by real application, I mean, one with a graphical user interface. But now that we’ve broached the topic, let’s go ahead and build an example WPF application. WPF stands for Windows Presentation Foundation. It’s one of the APIs inside of the.NET Framework class library that you use to build Windows applications. In other words, applications that are executed on the Windows desktop, not web pages that are executed on a server, and their markup is delivered into a browser but a true application that’s running on the end-users desktop. I’m going to File New Project, and here I want to make sure to choose WPF application. It should be one of the templates that are installed in the new project dialog. What I’m going to call this is, “WPFEvents” like so, and then click “Okay”. This is not going to be a tutorial on how to create Windows presentation, application, interfaces, or how to work with it, but I just want to show you the basics are generally the same. Here we have a basic application, we can actually run the application, it will do nothing at all. We just get a white form on screen. But I want to go to my toolbox over here on the left-hand side, and I’ll even pin it down briefly. Then inside of here, where I’ll go is to this rolled-up area called common WPF controls. Now. What you see on screen might be a little bit different than what I see on my screen. Just make sure you’re working inside of this MainWindow.xaml, and that you see some visual representation of your form here in the main area. You can ignore everything below. That’s the actual markup that will generate what you see visually here. We’re only going to work with the visual editor but know that there’s some markup that’s going on to produce this. But again, that’s a topic for another day. I’m going to drag and drop a button onto the design surface like so. I’m going to go over here to the Properties window on the right-hand side. This will allow me to set various attributes of that object, that visual object. For example, I can change the content to, “Click me” like so. I’m also going to add a label, control. I’m going to drag and drop it anywhere on this design surface. I’m going to remove the content completely, but I am going to change the name to, “myLabel” like so. Now, what I want to do is print out the phrase Hello world, whenever somebody clicks the “Click me” button. I’m going to choose the “Click me” button again by selecting it here in the visual editor, and then I’m going to look for this little lightning bolt over here in the Properties window and click the lightning bolt. This will show me a list of all of the events that this single control, this button can raise. Now, a lot of these are going to be for very specific situations, and we can ignore the vast majority of these. But the most important one here at the top is the click event. Now, I can write C# code that will execute as a result of this click event being raised by the .NET Framework because somebody, the user clicked on that “Click me” button. I’m just going to double click here in this white area, and when I double click in the white area, it created this button click method stub. This is going to be my event handler code. Let me use the auto-hide PIN to get rid of that, so I can see this. Here what I’m going to do is type in myLabel.content equals “Hello world” like so. I’m going to save my work, and then I’m going to start the application by running it. I’m going to click the “Click me” button and it displays the word “Hello world” inside of the little label. Now, what you didn’t realize is that maybe that whenever we double-clicked inside of Visual Studio in this little white area right here, it created a event handler for us, and it wired up or attached or registered that event to this button. You might wonder, well, where is the code that looks something like button.click plus equals, where’s that code at? Well, that’s a little bit difficult to describe if you take a look at this markup code here at the bottom and we scroll all the way to the right, that is essentially what happens right here. This code will get converted into C# at the point of compilation, and it will create that little snippet that we were used to looking at in the previous code example. However, I can create a second event handler in C#. By doing this, let’s go to the toolbox and I’m going to actually grab another label and just plop it down anywhere, and I’m going to select that label and they go to the Properties qindow and I’ll change this to be named my other label, and then I want to change the actual content of that label to be blank as well. Now what I want to do then is go to the MainWindow.xaml.cs, and here I’m going to go button underscore dot click plus equals and I could click “TAB to insert” but I’m not going to do that. I’m going to name this manually myself. But in my other click like so and then I hit Enter on the keyboard or actually I’m going to hit that. Now I’m going to, you can see that I get a red squiggly line. I’m going to put my mouse cursor on that line and hit Control period and then choose generate the method button underscore MyOtherClick and it does it for me, and you’ll see something that looks very familiar here, a method stub with the not implemented exception. Here I’m going to say myotherlabel.content equals “Hello again”, like so. Now if I did this correctly, whenever my user clicks the button, it will not only fire off this event handler, but then also this event handler. This event handler, we wired up manually using the technique that we learned in the previous code example. Let’s just run it, and make sure this actually works, and it does. The same principles are at play here. The difference is the vast number of events that are accessible to every single visual control in your toolbox whenever you’re working with the Windows Presentation Foundation API. The main takeaway of this lesson is that events are all around us, and especially whenever we’re working with Windows and web applications, we’re going to write our code in methods that respond to specific events that are raised by the .NET Framework runtime in response to events that are published by the various objects inside of our Windows apps, our web apps, and so on. We can either rely on Visual Studio to wire things up for us in a very quick and elegant way like we saw here in our XAML code, where we let it essentially do the wiring for us. Or we can take control of that process of wiring, of attaching, of registering an event handler to a specific event, and then write the code ourselves to actually respond to that event being raised. Again, extremely important. Hopefully, that’s the next logical step for you is to move on to other APIs, whether it be something like ASP.net or WPF like we’ve worked with a little bit right here or the Universal Windows Platform to build Windows Store applications. You’ll need to know these concepts for all of those. That pretty much wraps up this lesson and this entire course. We’ll have a couple of closing comments in the next video, and then that’s it. We’ll see you there. Thanks. Congratulations. You did it. You made it all the way to the end. That’s a huge accomplishment, don’t sell yourself short. When I look at the given views for our course, I typically see the first two or three videos in the course have an astronomical number of views, and then it begins to tail off over time until you get to the very end, you see a rather small percentage of those who started actually finishing the course. Then it used to concern me thinking, maybe I could be a little bit more engaging and keep people’s interest longer but good folks at Microsoft Virtual Academy assured me that that happens across the board with every course. I think what’s really going on is that everybody has the best of intentions to follow through to watch an entire course. But then life happens, distractions pop up, maybe changes in priority present themselves they interrupt or completely halt progress. But the good news is that is not you, you were able to make it all the way through to the end and now you’re well on your way to mastering C-sharp, or at least learning more about C-sharp. Then from here, learning more about.Net, picking a user interface technology, whether for web windows or mobile, maybe learning more about databases, maybe using C-sharp to access APIs around the Internet. We’ll talk about some of those things that you could learn as you move on from here a little bit later in this video. But soon you’re going to be building your own applications, whether for yourself, for your employer, maybe your future employer. But whatever the case might be congratulations, I really encourage you to continue your momentum. Don’t stop here, keep pushing forward, keep taking baby steps on a daily basis. As you know, daily progress, no matter how seemingly insignificant, is how you make real improvements in your life, it’s how you add skills to your skill-set and you’ve taken this great first step in the right direction and I’m proud of you can’t say that enough, great job, and I’ll continue to encourage you throughout this lesson. But I want to wrap up this series in this lesson and provide a few suggestions about where to look for answers whenever they pop up from here on out, as inevitably you can continue by building applications and learning more about the various APIs that are available to C-sharp developers. We’re also going to talk about the right way and the wrong way to ask for help out on the Internet. Then I’ll make a few suggestions on topics that you might want to investigate from here on out as you continue your self-directed training. But before I get started in earnest, let me say that some of the ideas that we talked about here, especially some of the more advanced concepts that I hinted at or that I said, you can let this go in one ear and out the other, I just wanted to show it to you up briefly. Some of these things could require weeks or months or even years of thought work before your mind is really able to accept them and digest them. I know I’ve personally spent hours just staring at a wall, thinking about some programming concept, trying to wrap my head around it. The mind needs quiet time to reflect. You need to put yourself into a position to succeed by giving your mind the time to discover, the time to ask the crucial questions, the time to allow those neurons to make those vital connections. Honestly, there are things that I learned about 10 years ago that I’m still trying to really wrap my head around, figure out what this means overall, in what contexts it applies, things like that. Many times I might need to read different books and articles, watch videos, and to hear what different authors have to say about a given topic before it finally resonates with me and I really understand what the topic is, how it pertains to me, what do I need to do with it? Things like that. Each author who talks or writes about a given topic can say things in just a little bit differently, and sometimes that can finally unlock something for me. Don’t forget to keep pushing forward and keep learning because there’s always answers out there. But ultimately, I hope you realize that you really don’t need to know everything right away to get started and to be productive right now. You don’t have to be an expert first before you can begin to write software. In fact, some concepts really only make sense after you have more experience. Once you’ve made some mistakes, or you can see where a given idea and Oh I see where that applies, I could use that here in this scenario, that finally makes sense to me why I would want to do that. Adjectory in a program is a good example and there’s some others too. I titled this lesson, where do you go from here? My intent was to answer that in two different ways. First of all, where do you go from here whenever you have a problem and you’re having a hard time resolving the problem and getting back on your feet again? There’s a good chance at some point as you’re learning, as you’re building applications, you’re going to run into error messages or something that just doesn’t make any sense. It happens to everybody. But I would encourage you do not fret, I think in fact, what makes programming such a vital skill is learning how to solve problems that combine your existing knowledge with your ability to reason through what could be the problem and then your ability to research and perform research on a given problem until you come up with the solution to it. The good news is that there is this large community of other developers inside and outside of Microsoft that can help nudge you and get you past these problems. These people write blog posts, they answer questions in the various forums, they write books, they record screencast video tutorials like this one. You can tap into that community of knowledge at any time. But let me give you a few tips on how to utilize that community in the most effective way. Let’s suppose that you do hit a wall. You’re experiencing some issue with your application, it’s not behaving the way that you expected, maybe you’re getting some strange error message popping up every time you try to debug your application. Where do you start to debug this to pick apart the problem and get to the root issue? First of all, I research using key phrases directly from the error message itself, and I can’t emphasize how vitally important that is. If there’s an error number or a specific phrase that I can latch on to and I can “surround those” as I type in my query to Bing.com, that always helps me get closer to a resolution. I might spend 10-15 minutes scanning through various blogs and forum posts or on MSDN as search results pop up for these sources in order to find a potential solution. If I’m mindful about my search terms, I almost always find a solution. I think the reason why a lot of beginners fail with finding solutions to the problems is because they become impatient or they don’t use the exact error messages in their searches, and they don’t know how to search correctly, and they’re not willing to put in the time to actually read through pages and pages of content to find a solution to the problem. I can’t emphasize enough using the exact phrase inside the error message that you see on screen “surrounded”, will get you closer to finding a resolution to the issue that you’re having. There are always usually people with other similar issues that are posted and then explain what they did to actually solve that particular issue, so research is vital. I think actually one vital skill as a modern software developer is you become great at search. Searching on the Internet to help solve issues that you run into is such a vital skill. Now, it might seem easier to go directly to the forums immediately and to post a question to the forums in hopes that somebody else can help solve your problem for you. But I assure you that it will actually take longer to ask the question and get an answer than it would if you spent the time searching, refining your searches, and so on until you find a solution to your problem. Frankly, I almost never have to ask a question in the forums because a simple search will almost always yield a clue to what I did wrong or what the core issue is. In fact, I get embarrassed when I have to ask questions. Maybe that’s a bad attitude to have, but I don’t want to burden other people with when they could be answering other legitimate questions, so I go overboard and try to figure out the issue on my own. Now, virtually any issue that you run into, I’m almost positive that somebody else has at some point run into that issue before you have, and they’ve already posted the solution to that problem online. You just need to get out there and find it. If you get good at doing research, doing searches on the Internet to help find solutions to your problems, then it’ll get you back on your feet faster than again, posting into a forum and asking other people for help. Now, let’s suppose that you’re at your wit’s end and you’ve done searches and there’s nothing out there that really seems to apply to your situation. Nothing you’ve tried actually works to resolve your problem, maybe at that point, you need to ask for help. That’s fine. Here’s what you really need to do whenever you ask for help. You need to ask your question in such a way that you’re going to get a resolution and how you ask your question is important. You need to be an empathetic requester. In other words, you need to get people who are willing to help all the information they need to get you back on your feet again to pinpoint the issue and then isolate the issue and prescribe a solution. This means that you need to, first of all, clearly state your request. There’s a checklist that I have in my mind of the things that you need to do. Some of these will be obvious and some of them you may have not considered before so let me just go through them real quick here. First of all, you should start by posting your question in the right place. Find the right category in the given forum or use the correct tags for your post so that the right people are looking at your questions. Posting a C-sharp question in a visual basic form is not going to be all that productive, in fact you’ll probably get chided for it. Secondly, you also need to choose a simple clear title for your post so that it attracts the attention of the people who can help so that it saves everybody a lot of time. If I see a forum post that just says, please help, I usually just skip it. If it says link to objects queries yielding unexpected results, well, okay, that’s oddly specific. That might be something I can help with. I look like the person put some effort into concisely stating what the issue is. I’ll read the question and I’ll see if I can help. Third, a short synopsis of the issues that you’re having, including the exact error message, including the exact behavior you are expecting, and what you’re actually experiencing. Describe what you expected to happen, but what if it happened instead and keep it concise. Fourth, if you can at all possible include screenshots, and ideally you would go one step further and use some screen editing or image editing software and draw circles to draw the eye’s attention to those parts of the screenshot that are pertinent to your question. Fifth, if possible, include a code example. Make sure to change any super-secret information, passwords things of that nature before you post it, but without a code snippet, many problems are unsolvable. I can’t tell you how many times I get people writing e-mails and they’ll say, I’m having a problem with this what do you think the solution is? I’m like, show me some code, I need to see what you did to get to that point, and then maybe I can help you figure out what your issue is. Always include, if you can, a code snippet of the code that you think is causing the problem. Then be choosy about which code you choose to post. There’s nothing more frustrating than looking at somebody who posts like 200 lines of code and expecting me to go through it all when a lot of it doesn’t even pertain to the question at hand. I mean, you had to spend a little bit of time narrowing it down to a few things. You need to help me be empathetic to me, the person who’s willing to help you to identify those lines of code that might be involved in the issue. Number 6, if a given forum has special HTML tags or shortcodes that you can use to format the code or some other aspect of your question to help it stand out in the post, then you definitely should use it. Number 7, tell me, what have you done so far to try to resolve the issue? Did it change anything at all? Did it change anything? Did it help? Did this lead you to rule out certain possibilities? Again, empathize with me, the person who’s reading your question, trying to help you. This will result in a faster resolution. Otherwise, people will start with the obvious issues and then move forward. There’s that old joke, Hey, I’m having a problem with my computer and the technician asks, well, do you have it plugged in? Everybody says, Oh, the technician was, but there’s a reason why they do that. It’s because the most obvious answer is the one that most of the time works for people. Don’t be that guy make sure you already list out what it is that you try to do and you’ve eliminated it as a possibility. Number 8, tell me which operating system you’re using, which version Visual Studio and the DUnit framework, which programming language you’re using, which updates, service packs have been applied anything that you feel is pertinent to help me help you diagnose the issue that matters more than you might realize. Number 9, suppose that there’s a resolution to the issue, you figured it out. Awesome. Very cool. Maybe somebody made some suggestions that led you down to investigate some things and you finally figured it out that’s great. Take a moment, go back wherever you asked the question, and describe exactly what you did to resolve the issue step by step. Use that as a means of better understanding it yourself and articulating that will help you better understand the issue and what the solutions are. It makes you part of the community of the wealth of information that’s out there so that others in the future who have the same issue can look at your post and that you are feeding it back into the community just like you’re taking out of the community. Chances are that honestly, that person that you help in the future is you, I can’t tell you how many times that I found a resolution to something, and then months later, I hit up against the same thing, thinking to myself, I know I’ve solved this once and I’ll go searching for a solution and I’ll find the exact solution and I’ll read it. Oh, that was me, that was me who answered the question. It would be nice just to search for your solution online if you knew where it was, or at least be courteous to everyone else and your future self to post the answers to the questions that you have. Finally, absolutely 100 percent be polite, people don’t owe you an answer they don’t owe you anything there. If they’re going to help you, they’re going to do it out of the kindness of their hearts. They’re going to be doing it in their spare time as a means of maybe, furthering their own understanding, helping themselves grow but then also to help you grow as a software developer. Say please and thank you and be nice and then help other developers as you have the opportunity. I do sell training content, but I give a lot of it away for free. I do ask questions in the forums, but I answer a bunch too, make sure that you become part of that community and that you are feeding back into the community, you help, and you support, just like you’ve been supported by others. You might be wondering, where do you go to find this level of support, where you can ask questions. That depends. Typically, I’d recommend that you go to msdn.Microsoft.com here, let’s go out real quick. So, msdn.Microsoft.com/forums and it might redirect you based on where you are in the world. But typically you can choose from a number of different forums, so you definitely want to find the specific technology or language or whatever the case might be, or do a quick search for those keywords again right here inside of the MSD and forums. It is monitored by Microsoft employees, as well as people called Microsoft Most Valuable Professionals, or MVPs. MVPs are usually knowledgeable people who’ve demonstrated their willingness to help, and they’ve been identified by Microsoft as people who are willing to help and so they qualify for that based on some criteria, not the least of which is participation in these forums. Then there’s also another more comprehensive place you can take a look at Stack Exchange, programmers.stockexchange.com, and there might be one other place where you could go but also by the same company that has similar forums, depending on the type of information you’re looking for. Now, in my experience, Stack Exchange is a little bit iffier. It’s a little less beginner-friendly. Maybe that’s changed by the time that you visit, and I only say that it’s a little less friendly because not only will you be critiqued for how you ask your question, but very often if people do a search to help you and then they find that there’s already an existing question that’s similar enough to you, they’ll shot your question down. Just follow the rules, do an extensive search before you ask a duplicate question, don’t take offense to criticism about your question. Again, I’d recommend that you search long and hard before actually posting the question because I’m convinced that virtually everything that you could run into has been asked by somebody already. You just need to spend the time to find the answer that you’re looking for. I said that I would answer the question of where to go from here in two different ways, and I’ve answered the question of where to go whenever you have problems. But now I want to answer the question where do I go to learn more about application development, where do I go to learn more about software development? At this point, you’ve got a pretty good foundation of C-sharp basic knowledge of the C-sharp programming language.Net and a little bit about Visual Studio but there are still a lot of opportunities to practice what you know and to grow beyond that. No matter what type of application that you want to build, there are a few fundamental ideas that you need to be fundamentally acquainted with before you move on. First of all, I would recommend that you learn about relational databases like SQL Server, you learn how to access data that’s stored in a database using the Entity Framework, part of the.Net API for accessing data in your applications. Both SQL Server and the Entity Framework have visual tools that you can use inside a visual studio to drag and drop and configure your settings and selections and so spending some time not only learning about the tools and the APIs themselves, but then also these visual tools and start a visual studio can pay big dividends. You’ll want to quickly grow past that and learn how to write code and rely less on the visual designers and visual studio. But still, it’s a great tool to help you get to that point where you can be productive quickly. Next, you’re going to need to choose a presentation technology that you want to master, and this is really more about platform, honestly than just simple UI. So you have no lack of options, whether you want to build web or Windows applications or mobile applications or games or backend processes, whatever the case might be. So let’s say, for example, you want to build web applications. There’s a couple of different platforms. The older API is called asp.net web forms, and there’s a lot of code that was written on the Web Forms Platform API. But then there’s also a newer API, that’s called asp.net core MVC, and there are some huge differences between the two, but we don’t have enough time to talk about those. I had content on both of those topics on my own website debut. There’s Windows Forms, which is the older desktop API. Then there’s Windows Presentation Foundation, which is a newer API that companies use for building applications internally and then there’s the Universal Windows platform, which you use to build more consumer oriented applications, typically for sale on the Windows Store. There’s also the Xamarin platform, which Microsoft recently purchased at the time, I’m recording this for building true cross-platform apps for iOS and Android and even Windows Phone. Then there’s a third party called Unity 3D or 2D, depending on the type of game that you want to build. And so you might want to check out unity for building games. Now, if you’re not really sure about where you should go next and what you should learn next, I really would recommend that if you don’t already know each HTML5, CSS3 and JavaScript, that’s a great place to start. And I’ve created several fundamental series on Channel 9 that are aimed at each of these topics. They’re also available here on Microsoft Virtual Academy again at the time when I recorded this. Then beyond that, I recommend learning about the basic tenets of application architecture, particularly how to structure your code into layers of responsibility and what that even means. So splitting your code into layers of responsibility will help you build applications that can withstand the impact of change. And like I said earlier in the series, change comes from a number of different places. It could be changing business rules. It could be changing requirements, changes in the technology that’s available. It also comes from defects in your software, bug reports that come in and you need to make changes to fix those. But in each case, you can mitigate the negative impact of making changes in your code by encapsulating the responsibilities behind well-established APIs between each of the layers of responsibility. And I spend a lot of time talking about this, about application architecture on debut. So if that’s something that interests you, you definitely want to check that out. But from there, you want to learn more about basic software design patterns and tactics and techniques. And there are a few keywords that you’re going to want to learn about, and each of these can spawn an entire book, an entire video series. And I’ve already alluded to the topic of object oriented programming. That’s a huge topic that you definitely want to learn about first. If you can just get your mind wrapped around object oriented programming and how that changes the way that you create solutions to programming problems, then that’s a huge step in the right direction. But beyond that, you’re going to want to learn about the principles of software development, principles that guide you to write your code in a very object oriented way. There are some more generalized principles, like the drive principle. I don’t know that I’ve ever given it a name, but it’s essentially don’t repeat yourself. I said be leery of copying and pasting. When you do find yourself wanting to copy and paste code in multiple places in your application, you should be stopping yourself and thinking, how can I create this in such a way that I can reuse it? So don’t repeat yourself, put code, extract it out. That will be reused into its own method or class, and then reuse it from there. There’s also another principle called Yagni or Y-A-G-N-I. Which is you ain’t going to need it. Which means, yeah, you could probably set yourself up and architect your application in such a way that in the future you could expand, but you’re probably not going to need to do that. You ain’t going to need it. All right. Then there’s another principle or idea called dependency injection, which is super important. It’s a design pattern that guides you towards building loosely coupled objects that then can be swapped in and out of the solution, and you’ll want to learn about dependency injection. It’s really crucial to building some of the new style applications using like the ASP.Net Core MVC, which relies heavily on dependency injection. There’s also a set of principles called Solid, S-O-L-I-D. Each of those stand for a different sub principle. They help you realize the promise of object oriented programming inside of your applications. So again, a lot of ideas that are more conceptual in nature and less code syntax or tool oriented. All right. You’re also going to want to learn about the process of software development, so the workflow surrounding software development and managing software projects. So specifically, you’re going to want to learn about the tools and the techniques that you use whenever you work inside of a team sharing source code between team members using a source code repository like Git or like Visual Studio Online’s implementation of Git and their own internal source code repository tool. You’re definitely going to want to learn about building unit tests, which are tiny little code based tests that continually are testing your code every time you write. Some people have even gone as far to say that you should be writing those little unit tests first and then you write the actual production code that satisfies those unit tests. Now, whenever there’s a change made in the system, you can see what the impact of that change is because you’ll begin to see these little tests start filling, that is a process called test driven development, and some people swear by it. Other people swear at it. So you’re also going to want to learn about agile project management, agile software development techniques, defining requirements in user stories, playing a game called planning poker to determine what features can we include in a given iteration of our software building process, using agile boards to manage assigned tasks between the various software developers on the team. You’re going to want to learn about the nature of iterative development. How to use that term iteration. So you want to learn about what are iterations and one of the goals of iterations and why they’re useful. You’ll want to learn about developing a spike of functionality all the way through all the layers of responsibility in your system. So I’ve given you probably what, several dozen different key terms that you could use as a launching point to search on. Honestly, if you were to look at all those terms that I just use, it’ll take several years to learn about all those things, even in a general way. But fortunately again, you don’t have to know at all to get started to be productive today. So, yeah, there’s so much to learn in so little time. But it’s what makes software development fun and makes it exciting because there’s always something new to learn and some new technique to try. I’ve had friends at Microsoft, actually confide in me that it’s a challenge for them to keep up with it all. Nobody just knows all this stuff automatically. It’s a challenge for everyone, everybody to keep up with. Nobody just knows it all. It just keeps evolving. You just have to really commit yourself to learning. I realized some time ago that my full time job is not creating video content or training content for developers, my full time job is really learning. And then if I create training content, that’s really a byproduct of all the learning that I’m doing, the value that I have to somebody else is my knowledge. And so without that is the core piece of what I do. Whether it’s building applications for somebody or creating training content, they’re only interested in me because of my knowledge. Then how I apply that knowledge is a byproduct of actually gaining the knowledge. So you have to really commit to learning. And I know since you’re here on Microsoft Virtual Academy that you’ve already done that to some degree. There’s a whole bunch of great resources out that are available on the Internet, not the least of which are Channel 9 and Microsoft Virtual Academy. Obviously, there’s MSDN, as we looked at earlier in the series. However, before I close this out, let me make one final plug for you to visit my website. If you haven’t already developeruniversity@devu.com, is there on screen. I’ve designed the courses there specifically for someone who’s a beginner to help them get up and running as quickly as possible, pointing out what I feel like they really need to know in order to master key ideas that will lead them to get jobs in the software development industry, providing homework exercises and quizzes. But more importantly, coding challenges that force people to write and to develop the muscles of your mind that allow you to pick apart a problem and create a solution for it. All right. So please check out devu.com whenever you get a chance. All right. So as I close here, I hope you found this course to be valuable and this lesson to be valuable. If there’s anything that I can ever do to help you, please let me know. You can find me out on Twitter. I sometimes go out there. Hit me up on Facebook or, you can write me an e-mail. But finally, as we close out, I sincerely wish you the best of luck in your career. C-sharp in software development is such an exciting field to be a part of, and I’m really excited for you. So good luck. Thank you for watching this series.

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog

  • JavaScript Concepts: Variables, Data Types, Syntax, and Functions by Bob Tabor

    JavaScript Concepts: Variables, Data Types, Syntax, and Functions by Bob Tabor

    The source provides instruction for learning JavaScript. It covers creating files and directories for code and explains the structure of JavaScript statements, including operators, operands, and expressions. Various JavaScript concepts are explained, such as variables, data types, coercion, scope, functions, objects, arrays, loops, the ‘this’ keyword, classes, inheritance, template literals, regular expressions, and built-in native objects. The material also touches on design patterns like the module pattern and new JavaScript features like arrow functions. The explanation includes examples in both Node.js and web browser contexts.

    JavaScript Fundamentals: A Comprehensive Study Guide

    Quiz

    1. What is JavaScript and who is it designed for? JavaScript is a programming language designed primarily for beginners, especially those familiar with HTML and CSS, and even individuals with no prior programming experience.
    2. What problem is Babel.js designed to solve? Babel.js addresses the issue of browser compatibility by transpiling newer JavaScript code into older, more widely supported versions, ensuring functionality across various browsers, including outdated ones.
    3. Explain the difference between declaring and initializing a variable. Declaring a variable involves creating a named storage location in memory using the let keyword, while initializing assigns an initial value to that variable at the time of its declaration.
    4. What are the rules for naming variables in JavaScript? Variable names must begin with a letter, dollar sign ($), or underscore (_), can contain letters, numbers, dollar signs, or underscores, and cannot be keywords or contain spaces. Additionally, variable names are case-sensitive.
    5. What is coercion in JavaScript, and why can it be problematic? Coercion is the automatic conversion of one data type to another. This can lead to unexpected behavior, especially when performing operations on values of different types (e.g., adding a number and a string).
    6. Explain the difference between the equality operator (==) and the strict equality operator (===). The equality operator (==) checks for value equality after performing type coercion if necessary, while the strict equality operator (===) checks for both value and type equality without coercion.
    7. Explain the purpose of the break statement within a switch statement. The break statement is used to exit a switch statement after a case match has been found and its corresponding code has been executed, preventing the execution of subsequent cases.
    8. What is variable scope? Variable scope defines the accessibility and lifetime of a variable within a program, determining where it can be accessed and when it is removed from memory.
    9. Explain the module pattern in JavaScript and what problem it aims to solve. The module pattern is a design pattern used to encapsulate code within a module, creating private and public scopes. It primarily solves the issue of polluting the global namespace.
    10. What are template literals in JavaScript? Template literals are string literals that allow embedded expressions. They use backticks (`) instead of single or double quotes and can contain placeholders (${expression}) that are replaced with the values of the expressions.

    Answer Key

    1. JavaScript is a programming language designed primarily for beginners, especially those familiar with HTML and CSS, and even individuals with no prior programming experience.
    2. Babel.js addresses the issue of browser compatibility by transpiling newer JavaScript code into older, more widely supported versions, ensuring functionality across various browsers, including outdated ones.
    3. Declaring a variable involves creating a named storage location in memory using the let keyword, while initializing assigns an initial value to that variable at the time of its declaration.
    4. Variable names must begin with a letter, dollar sign ($), or underscore (_), can contain letters, numbers, dollar signs, or underscores, and cannot be keywords or contain spaces. Additionally, variable names are case-sensitive.
    5. Coercion is the automatic conversion of one data type to another. This can lead to unexpected behavior, especially when performing operations on values of different types (e.g., adding a number and a string).
    6. The equality operator (==) checks for value equality after performing type coercion if necessary, while the strict equality operator (===) checks for both value and type equality without coercion.
    7. The break statement is used to exit a switch statement after a case match has been found and its corresponding code has been executed, preventing the execution of subsequent cases.
    8. Variable scope defines the accessibility and lifetime of a variable within a program, determining where it can be accessed and when it is removed from memory.
    9. The module pattern is a design pattern used to encapsulate code within a module, creating private and public scopes. It primarily solves the issue of polluting the global namespace.
    10. Template literals are string literals that allow embedded expressions. They use backticks (`) instead of single or double quotes and can contain placeholders (${expression}) that are replaced with the values of the expressions.

    Essay Questions

    1. Discuss the importance of browser compatibility in web development. Explain how tools like Babel.js contribute to addressing this challenge and enabling developers to use modern JavaScript features while maintaining support for older browsers.
    2. Explain the concept of variable scope in JavaScript, detailing the differences between global, function, and block scope. Provide examples to illustrate how variable scope affects the accessibility and lifetime of variables within a program.
    3. Discuss the advantages and disadvantages of using the module pattern in JavaScript for code organization and encapsulation. Compare and contrast the module pattern with the revealing module pattern, highlighting their differences and potential use cases.
    4. Explain the concept of closures in JavaScript. How do closures enable the association of data with functions? Provide an example to demonstrate how closures can be used to create functions with persistent state.
    5. Explain the behavior of the “this” keyword in JavaScript and its implications for object-oriented programming.

    Glossary of Key Terms

    • Transpilation: Converting source code from one programming language (or version) to another.
    • Variable Declaration: Creating a named storage location in memory to hold a value.
    • Variable Initialization: Assigning an initial value to a variable at the time of its declaration.
    • Identifier: The name given to a variable, function, or other programming element.
    • Keyword: A reserved word in a programming language with a specific meaning and purpose.
    • Coercion: Automatic conversion of one data type to another.
    • Data Type: The classification of a value, determining the kind of data that can be stored and the operations that can be performed on it (e.g., number, string, boolean).
    • Assignment Operator: A symbol (=) used to assign a value to a variable.
    • Operator Precedence: The order in which operations are performed in an expression.
    • Operand: A value or variable on which an operator acts.
    • Expression: A combination of values, variables, and operators that evaluates to a single value.
    • Statement: A complete instruction in a programming language.
    • Function Declaration: Defining a function with a specified name, parameters, and body.
    • Function Expression: Creating a function as part of an expression.
    • Function Invocation: Calling or executing a function.
    • Argument (Parameter): A value passed into a function when it is called.
    • Return Value: The value returned by a function after it has completed execution.
    • Code Block: A group of statements enclosed in curly braces ({}).
    • Decision Statement: A statement that allows the execution of different code blocks based on a condition (e.g., if, switch).
    • Iteration Statement: A statement that allows a block of code to be executed repeatedly (e.g., for, while).
    • Variable Scope: The region of a program where a variable is accessible.
    • Lexical Scope: A variable’s scope is determined by its location within the source code.
    • Global Scope: Variables declared outside of any function or block have global scope.
    • Function Scope: Variables declared inside a function have function scope.
    • Block Scope: Variables declared inside a block (e.g., if statement, loop) with let or const have block scope.
    • Module Pattern: A design pattern used to encapsulate code within a module, creating private and public scopes.
    • Immediately Invoked Function Expression (IIFE): A function expression that is executed immediately after it is created.
    • Closure: A function that retains access to variables from its surrounding scope even after the outer function has finished executing.
    • Truthy/Falsy: Values that are implicitly converted to true or false when evaluated in a boolean context.
    • Template Literals: String literals that allow embedded expressions, enclosed in backticks (`).
    • Regular Expression: A pattern used to match and manipulate strings.
    • Arrow Function: A concise syntax for writing function expressions.
    • DOM (Document Object Model): A programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content.
    • Event Listener: A function that is called when a specific event occurs (e.g., click, mouseover).

    JavaScript Fundamentals: A Beginner’s Guide

    Here’s a detailed briefing document summarizing the main themes and ideas from the provided source, with direct quotes to illustrate key points.

    Briefing Document: JavaScript Fundamentals

    Overview:

    This document summarizes a JavaScript course intended for absolute beginners to programming. The course covers basic JavaScript syntax, data types, operators, control flow (decision statements, iteration), functions, object-oriented programming principles, DOM manipulation, and more advanced concepts like closures and the module pattern. It emphasizes the core language rather than web development aspects, initially focusing on console-based applications before discussing browser implementation.

    Main Themes and Key Ideas:

    1. Target Audience and Scope:
    • The course is designed for individuals with HTML and CSS knowledge who want to learn JavaScript, targeting absolute beginners to programming in general. “This course is aimed at those who are absolute beginners so beginners to javascript and frankly given that we’re going to discuss some very basic things like if statements and for loops it’s really designed for those who are beginners to programming in general.”
    • It focuses on the JavaScript language itself before delving into web browser implementations. “My focus is the javascript language the pure language not web development necessarily although we will discuss javascript in the context of the web browser at the very end of this course.”
    • The course covers the Javascript language itself, not necessarily web development.
    1. JavaScript Versions and Compatibility:
    • The importance of browser compatibility is discussed, highlighting the issue of older browsers not supporting newer JavaScript features. “hat are viewing web pages with browsers that were created 10 years ago so clearly in these cases the newer features of javascript many of which we’ll discuss in this course will not be available in those browsers and your javascript won’t even work in those web browsers.”
    • Two approaches to address compatibility: writing code friendly to older browsers or using transpilers like Babel to convert modern JavaScript to older versions. “You can either attempt to write your code in such a way that it is is as friendly as possible to those older web browsers or you can use a tool which will transpile your javascript code.”
    • The website “can i use” is suggested to check browser support for specific JavaScript features.
    1. Importance of Precision and Syntax:
    • Emphasis on the need for precise syntax in programming languages. “You can’t just write a text message full of lowercase letters and things of that nature that would make it a well-formed english sentence and you’re you’re relying on your the person receiving that text message to understand what you’re trying to say the computer doesn’t work that way it means it needs to know exactly what you’re saying and so you have to be precise precision is the key as a software developer.”
    • Use of code comments ( // ) to exclude lines from compilation.
    1. Variables and Data Types:
    • A variable is defined as “basically just a a an area in the computer’s memory where we’re storing a value.”
    • Explanation of variable declaration using the let keyword. “A keyword is something like let… essentially think of it like a verb in the english language. It’s an instruction to the javascript compiler that we want to do something…”
    • Rules and conventions for naming variables (identifiers). Identifiers must begin with a letter, dollar sign, or underscore and can contain letters, numbers, dollar signs, or underscores, but no other special characters. Identifiers cannot contain spaces and cannot be keywords.
    • Discussion of data types: number, boolean, string, and undefined. “The variable itself does not have a data type only the values that we store inside the variables have the data type.”
    • The typeof operator is introduced to determine a variable’s data type.
    • Coercion is introduced with example let a = 7; let b = “6”; let c = a+b;, which yields 76, and parsing b to an integer solves it.
    • NaN is discussed as representing “not a number” if an illegal parsing is attempted.
    1. Operators and Expressions:
    • Definitions of operators (keywords, symbols) and operands (identifiers, variables, functions).
    • “By combining operators and operands we create expressions that are then used to compose statements”.
    • Examples of different types of operators: assignment (=), arithmetic (+, -, *, /), increment/decrement (++, –), comparison (==, ===, !=, !==), logical (&&, ||).
    • Discussion of the order of operations and using parentheses to control evaluation.
    • Introduction of the member accessor operator (.) for accessing object properties.
    1. Control Flow: Decision Statements and Iteration:
    • Explanation of decision statements: if, else if, else, switch, and the ternary operator.
    • The structure of the if statement is outlined. if (some expression that expression should equal true or false)
    • “The ternary operator has kind of got several parts here there’s an expression there’s a question mark that that has true or false ramifications.”
    • The structure of the switch statement is outlined, and the need for break statements to prevent fallthrough.
    • Explanation of the ternary operator for inline conditional evaluation.
    • Iteration statements: for and while loops.
    • “Iterations allow us to loop through a body of code a block of code a number of times until a certain condition is met.”
    • Example showing how to iterate through an array using a for loop.
    • The “break” keyword allows premature escape from iterations.
    1. Variable Scope:
    • “When I use the term scope I mean variables are a little bit like people in so much that variables have a lifespan they’re born they do work and then they die and they’re removed from computers memory when they go out of scope”.
    • Scope is defined as the region of a program where a variable can be accessed.
    • Variables declared outside a function have global scope and can be accessed within the function. Variables declared inside a function have local scope and cannot be accessed outside the function.
    1. Functions:
    • A “method as a function that belongs to or rather is defined inside of an object”.
    • The declaration and invocation of functions. “To actually invoke a function we have to use the function invocation operator in this case it’s the opening close parentheses.”
    • Passing arguments to functions. “We’re able to reuse that code but change it up by passing in the name that I wanted to say hello to.”
    • Returning values from functions using the return keyword.
    • Discussion of avoiding creating variables in the global scope.
    • Returning a function from a function.
    • Example of a function that returns a string like one using the keyword return.
    1. Objects and the this Keyword:
    • Definition of objects as collections of properties (key-value pairs).
    • “Simple objects have a single property, other objects can have more properties including other objects.
    • Creating object literals.
    • Accessing object properties using dot notation (.) and bracket notation ([]).
    • Introduction of the this keyword, emphasizing that its value depends on how a function is called.
    • this depends on how a given function is called, not necessarily how/where it was created.
    • Examples showing how this refers to the global object in a regular function call (in non-strict mode).
    • Using the call() and apply() methods to explicitly set the value of this.
    • The this keyword in the context of a web page is different.
    • Use the id property in a button to specify a unique identifier for this DOM element.
    1. Template Literals:
    • Template literals are delimited with backticks (“`) and allow string interpolation.
    • They’re “a nice addition to the javascript language here again they can make your code more compact and readable allowing you to do some interesting things in line that would require a lot of appending of strings previously.”
    • Example demonstrating how to embed expressions within template literals using ${expression}.
    • Ability to create multi-line strings without concatenation.
    1. Regular Expressions (Regex):
    • Regular expressions are patterns used to match character combinations in strings.
    • Use the test() method to check if a string matches a pattern.
    • Use the replace() method to replace matched patterns with a new string.
    • There’s a lot to Regex, but a simpler approach is to use methods for checking if a string matches a pattern.
    1. Arrow Functions:
    • Arrow functions provide a more concise syntax for writing function expressions.
    • “Arrow functions… just get rid of the keyword function but this remains and it allows us to define an input parameter name inside of or after the fat arrow and inside of the body I can go console.log…”
    • Basic syntax: (parameters) => expression or (parameters) => { statements }.
    1. Truthy and Falsy Values:
    • Understanding truthy and falsy values in JavaScript is crucial for conditional evaluations.
    • Falsy values: false, 0, “” (empty string), null, undefined, and NaN.
    • Truthy values: All values that are not falsy.
    1. Date and Time:
    • Creating Date objects using the new Date() constructor.
    • Using methods like getDate(), getDay(), getMonth(), getFullYear(), and getTime() to extract date and time components.
    • Calculating elapsed time between two dates.
    1. String Methods:
    • split(): Splits a string into an array of substrings based on a separator.
    • slice() and substring(): Extracts a portion of a string.
    • endsWith() and startsWith(): Checks if a string ends or starts with a specified string.
    • includes(): Checks if a string contains a specified substring.
    • repeat(): Repeats a string a specified number of times.
    • trim(): Removes whitespace from both ends of a string.
    1. Array Methods:
    • push() and pop(): Adds/removes elements from the end of an array.
    • shift() and unshift(): Adds/removes elements from the beginning of an array.
    • splice(): Adds or removes elements from any position in an array.
    • concat(): Concatenates two or more arrays.
    • slice(): Creates a new array containing a portion of an existing array.
    • join(): Joins all elements of an array into a string.
    • sort(): Sorts the elements of an array.
    1. Error Handling (Try/Catch):
    • Using try, catch, and finally blocks to handle exceptions.
    • The try block executes normally, but if an exception occurs, the catch block gets invoked, and at the very end, regardless, is the finally.
    • Throwing custom exceptions using throw new Error().
    1. DOM Manipulation:
    • Selecting DOM elements using document.getElementById().
    • Adding event listeners to DOM elements using addEventListener().
    • Creating new DOM elements using document.createElement().
    • Manipulating element attributes and styles.
    1. Module Pattern and Closures:
    • The module pattern uses an immediately invoked function expression (IIFE) to create a private scope and return an object with public methods.
    • “These are topics that could have easily been covered much earlier in the course but because I was trying to get somewhere I left those details off till now so hopefully you don’t mind that we’re going to circle back and fill in some of the or backfill some of the topics that we just didn’t cover in a lot of depth”.
    • “Closures create lexical environment” for each closure instance to define an environment.
    • Closures allow a function to access variables from its surrounding scope even after the outer function has finished executing.

    Conclusion:

    This course provides a comprehensive introduction to JavaScript for absolute beginners. It systematically covers fundamental concepts, equipping learners with the knowledge to write basic JavaScript programs. The emphasis on core language features and progressive exploration of concepts helps build a strong foundation for further exploration of web development and other JavaScript applications.

    JavaScript Fundamentals: A Concise Guide

    Javascript FAQ

    • What is the primary goal of this JavaScript course?
    • The course aims to teach JavaScript to absolute beginners, even those new to programming in general. It focuses on the core JavaScript language itself, rather than web development aspects, although it does touch on JavaScript’s use in web browsers at the end. The course emphasizes precision and understanding how to write code that a computer can interpret accurately.
    • What are some important considerations when choosing which JavaScript features to use, given different browser compatibility levels?
    • You have two main choices: write code that is compatible with older browsers, or use a tool like Babel to transpile your modern JavaScript code into an older version that is compatible with most browsers. The website “Can I Use” helps determine browser support for specific JavaScript features.
    • What are variables in JavaScript, and what are the rules for naming them?
    • A variable is a named storage location in the computer’s memory that can hold a value. Variable names (identifiers) must start with a letter, dollar sign, or underscore. They can then contain letters, numbers, dollar signs, or underscores, but no other special characters (including spaces). Variable names are case-sensitive, and you cannot use reserved JavaScript keywords as variable names.
    • What are data types in JavaScript, and how does JavaScript handle them?
    • Data types define the kind of data that a variable holds. JavaScript is dynamically typed, meaning the variable itself doesn’t have a fixed data type; only the value stored in the variable has a data type. Common data types include number, string, boolean, and undefined. JavaScript can perform type coercion, automatically converting data types in certain situations (like concatenating a number and a string), although this can sometimes lead to unexpected results.
    • What are operators and operands, and how do they relate to expressions and statements?
    • Operators are symbols or keywords that perform actions (like +, =, let), while operands are the values that operators act upon (variables, literals, function calls). Operators and operands form expressions, which evaluate to a single value. Expressions are used to compose statements, which are instructions that the JavaScript interpreter can execute.
    • What are functions in JavaScript, and how can we define and use them?
    • Functions are reusable blocks of code that perform specific tasks. You can define functions using function declarations, which involve giving a name to a code block. You can also create function expressions, assigning a function to a variable. To execute a function, you call it by its name followed by parentheses (the function invocation operator). Functions can accept input parameters (arguments) and return values.
    • What are the module pattern and revealing module pattern, and what problems do they solve?
    • The module pattern and revealing module pattern are design patterns used to encapsulate JavaScript code, reducing the impact on the global namespace and promoting code organization. They use immediately invoked function expressions (IIFEs) to create a private scope and return an object that exposes only specific variables and functions (the module’s “public” interface). The revealing module pattern makes it clearer what the “public” methods will be by declaring them at the end.
    • How does the this keyword work in JavaScript, and how can we control its value?
    • The this keyword refers to the context in which a function is called. Its value depends on how the function is invoked. When a function is called as a method of an object, this refers to that object. You can explicitly control the value of this using the call() and apply() methods. In arrow functions, this is lexically bound, meaning it inherits the this value from the surrounding scope.

    JavaScript Syntax Elements

    The sources discuss JavaScript syntax and some of its elements.

    Key aspects of JavaScript syntax:

    • Statements JavaScript files contain one or more statements that execute sequentially from top to bottom. A statement is a complete instruction, similar to a sentence in English.
    • Expressions Statements are made up of one or more expressions. Expressions consist of operators and operands. By combining operators and operands, expressions are created that are then used to compose statements.
    • Operators Operators are keywords or symbols that perform actions, such as the addition operator (+), string concatenation operator (+), and assignment operator (=).
    • Operands Operands are identifiers, such as variable names and function names. Programmers give operands their names.
    • Keywords Keywords are like verbs that instruct the JavaScript compiler to perform actions. Examples include let, var, and const.
    • End of line character A semicolon (;) typically indicates the end of a statement.
    • Code comments Double forward slashes (//) can be used to comment out a single line of code, instructing the compiler to ignore it. Multi-line comments can be created using /* to begin the comment and */ to end the comment.
    • Precision Being precise is key when writing code. The computer needs to know exactly what to do.
    • Data Types Values, not variables, have a data type, which describes what you intend to do with the data. Examples include number, boolean, and string.

    There are naming rules and conventions that need to be followed as developers. For example, code conventions include using camel casing, using descriptive and clear names, and being consistent in the style and naming conventions used.

    JavaScript Variable Declaration Guide

    Variable declaration in JavaScript involves reserving a space in the computer’s memory to store and retrieve data during an application’s lifespan. There are several parts to a variable declaration.

    Key aspects of variable declaration:

    • Keywords Keywords are a way to declare a variable.
    • let The let keyword is an instruction to the JavaScript compiler to create a variable. It declares a block-scoped local variable, optionally initializing it to a value. The recommendation is to abandon var unless it is required, and to use let instead.
    • const The const keyword is used when it is intended for the variable to never change its value. If a new value is assigned to a const variable, the JavaScript compiler will throw an error.
    • var The var keyword was the original way to declare a variable in JavaScript. However, its usage is nuanced and can be problematic for new developers.
    • Identifier An identifier is the name assigned to a variable so it can be referenced later.
    • Assignment operator The assignment operator (=) assigns a value to a variable.
    • Initialization Initialization refers to assigning a value to a variable at the same time it is declared. When a variable is declared but not initialized, its value is undefined. It is preferable to initialize variables at the moment of declaration.
    • Scope Scope refers to the accessibility of variables in different parts of the code. Variables declared outside of a function have global scope and can be accessed from anywhere in the code. Variables declared inside a function have local scope and can only be accessed within that function.

    There are several rules for naming variables:

    • All variable names must begin with a letter, a dollar sign ($), or an underscore (_).
    • Variable names can contain letters, numbers, dollar signs, or underscores, but no other special characters or spaces.
    • Keywords cannot be used as variable names.
    • Variable names are case-sensitive.

    There are also code conventions that are good practices to follow:

    • Variable names should be descriptive.
    • Camel casing should be used for multiple words, where the first word is lowercase and subsequent words have a capital letter.
    • Be consistent by following the same naming convention throughout the application.
    • Do not rely on case; avoid using the same name with different casing for different variables.

    JavaScript Function Execution: Definition, Syntax, and Scope

    Here’s a discussion of function execution based on the provided sources:

    • Definition A function is a block of code with a name that can be called to execute the code within the block. Functions are a primary construct in JavaScript for getting things done.
    • Parts of a Function A function includes a name/identifier, parentheses for arguments/input parameters, and curly braces to define the body of the function.
    • Function Declaration A function declaration begins with the keyword function, followed by an identifier (the function name), then parentheses (), and finally curly braces {} enclosing the code to be executed.
    • Calling a Function To execute a function, it needs to be called or invoked by its name, followed by parentheses (). This is the function invocation operator.
    • Arguments Arguments are values passed into the function when it is invoked, which the function can then use.
    • Function Expressions A function expression is similar to a function declaration, but it does not require a name. Function expressions are useful when a function is needed temporarily and will not be called again.
    • Return Values Functions can return values using the return keyword, passing data back to the caller.
    • Variable Assignment Functions can be assigned to variables, allowing the function to be invoked using the variable name and the function invocation operator.
    • Scope The location where a variable is defined determines its accessibility. Variables defined outside of a function are accessible inside the function, but variables defined inside a function are not accessible outside the function.
    • this Keyword The this keyword refers to the object that a function is associated with. The value of this depends on how the function is called.
    • Call and Apply The call and apply methods can be used to explicitly set the value of this inside a function.
    • Hoisting Function declarations are “hoisted” to the top of the execution environment, so they can be called before they are defined in the code.
    • Immediately Invoked Function Expressions (IIFE) An IIFE is a function expression that is defined and then immediately executed. This pattern is often used to create a private scope for variables and functions.
    • Arrow Functions Arrow functions provide a shorthand syntax for defining functions.

    JavaScript Object Creation Methods

    Object creation in JavaScript can be achieved through several methods, each with its own nuances.

    Object Literal Notation

    • Objects can be created using object literal notation, defining the object and its properties directly using curly braces {}.
    • Properties within the object are defined as name-value pairs, separated by colons.
    • The property names are identifiers, similar to variable names, and the values can be of any data type.
    • Each property definition is separated by a comma, except for the last one.
    • After the object is defined, it can be assigned to a variable.
    • For example: let car = { make: “BMW”, model: “745li”, year: 2010 };.

    Constructor Functions

    • Objects can also be created using constructor functions.
    • A constructor function is a regular JavaScript function that is called with the new keyword.
    • By convention, constructor functions are named with a capital letter.
    • The new keyword performs the following actions:
    • It creates a new empty object.
    • It sets the this value of the function to the new object.
    • It executes the function, adding properties and methods to the new object.
    • It returns the new object.
    • Inside the constructor function, the this keyword is used to refer to the object being created.
    • For example:
    • function Car(make, model, year) {
    • this.make = make;
    • this.model = model;
    • this.year = year;
    • }
    • let myCar = new Car(“BMW”, “745li”, 2010);

    Classes (Syntactic Sugar)

    • JavaScript also has a class syntax, introduced in later versions, which provides a more structured way to create objects and deal with inheritance, but it is essentially syntactic sugar over the existing prototype-based system.
    • Classes are declared using the class keyword, followed by the class name.
    • The constructor method is a special method within the class that is automatically called when a new object is created using the new keyword.
    • Methods can be defined within the class, outside the constructor.
    • Classes support inheritance using the extends keyword.
    • For example:
    • class Car {
    • constructor(make, model, year) {
    • this.make = make;
    • this.model = model;
    • this.year = year;
    • }
    • print() {
    • console.log(`${this.make} ${this.model} (${this.year})`;
    • }
    • }
    • class SportsCar extends Car {
    • revEngine() {
    • console.log(“Vroom goes the ” + this.model);
    • }
    • }
    • let mySportsCar = new SportsCar(“Dodge”, “Viper”, 2011);
    • mySportsCar.print(); // Output: Dodge Viper (2011)
    • mySportsCar.revEngine(); // Output: Vroom goes the Viper

    Object.create()

    • The Object.create() method can create a new object, using an existing object as the prototype.
    • This allows for prototypal inheritance, where the new object inherits properties and methods from the prototype object.
    • Changes to the prototype object can be reflected in the new object, and vice versa.
    • “`javascript
    • let originalCar = {
    • make: “BMW”,
    • model: “745li”,
    • year: 2010
    • };
    • let newCar = Object.create(originalCar);
    • console.log(newCar.make); // Output: BMW
    • “`
    JavaScript Fundamentals for Absolute Beginners

    The Original Text

    hi my name is bob tabor and in this course you’ll learn about javascript the language this course is aimed at those who are absolute beginners so beginners to javascript and frankly given that we’re going to discuss some very basic things like if statements and for loops it’s really designed for those who are beginners to programming in general so if you know some html and some css and you want to learn javascript awesome you’re in the right place also there’s nothing specific to windows in this course the tools that i use will be free and available in mac and linux as well so you should be able to follow along no matter which operating system you’re comfortable with using now my background is really not all that important but in case you’re curious i am a software developer by day and by night i run a website called developeruniversity or devview you can visit me at http://www.devview.com occasionally microsoft invites me to create courses and what you see here is a collaboration between myself and the good folks at microsoft virtual academy i’ve been creating courses like this since 2004 and i created a very successful version of a javascript course way back in 2011 it’s been viewed millions of times and i’ve got a lot of very positive feedback about it this is a rewrite a complete rewrite of that course because uh frankly javascript has changed dramatically in the what six or seven years since i originally recorded that course uh and so if you’re already a software developer coming from a different programming language just kind of pick back up what i said earlier this might move a little bit slow for you it just wasn’t designed with you in mind there might be some other courses that can move you through the the introductory material a little bit more quickly than what i plan on than than the pace that i plan to take with this course and my focus is the javascript language the pure language not web development necessarily although we will discuss javascript in the context of the web browser at the very end of this course but i felt like teaching javascript and how it’s implemented in the web browser clouded the discussion of javascript the language itself so we’re going to be writing what amounts to console or rather command line style applications to isolate javascript the language as purely and simply as possible without clouding it with a bunch of html and css and things like that we’re going to discuss the language we’ll discuss popular patterns that have emerged from the javascript development community to help overcome some of the challenges associated with working with such a highly dynamic language such a unique language and sometimes kind of a quirky language the last time that i recorded the course uh about javascript way back in 2011 the the course actually had a fairly long shelf life and so much has changed with javascript since then that uh i necessitated that i actually play catch-up and kind of learn some of the new features that were added because i wasn’t keeping my skill set uh up that’s how quickly things change out from under you if you’re not careful if you know anything about javascript you know that the community around javascript is moving extremely quickly it’s the most popular programming language not just in the web browser where there are hundreds of javascript frameworks and libraries that you can leverage in your own applications but it’s also becoming one of the most popular languages for server-side web development meaning the code that actually runs on a web server that can perform business logic that can interact with data storage uh databases and and other uh styles of data storage and we’re not going to talk about any of those topics in depth per se but it is important to know that it all starts with a basic understanding of the things that we will discuss in this course the absolute basics of javascript so since this course may have a long shelf life it’s important to know that some of the features of the latest version of javascript which i will be covering in this course may not yet be implemented in all web browsers depending on when you view this course and then uh you have to take into account that some of the people viewing your website for example might be using very old web browsers and so you have to keep that in account as well so i’m going to make two general suggestions and i’m going to try to remind you about these at the very end there are still people on the internet that are viewing web pages with browsers that were created 10 years ago so clearly in these cases the newer features of javascript many of which we’ll discuss in this course will not be available in those browsers and your javascript won’t even work in those web browsers so you have a choice at that point you can you can go one of two routes you can either attempt to write your code in such a way that it is is as friendly as possible to those older web browsers or you can use a tool which will transpile your javascript code that you write using the latest features of javascript it’ll transpile it back into a version of javascript that is compatible with all web browsers even those that were built 10 years ago and it uses a combination of techniques to accomplish this we’re not going to get into any of those but if you want to take the first tact if you want to be careful with the javascript that you write and only use those those original features i guess you can say of javascript or the early features of javascript there’s a website for you you want to take a look at this website called can i use and so we can take a look at maybe one of the newer features of javascript the let keyword i’ll type it in here in the search box can i use and it will show us the let keyword gives a quick description of what it is and then it will show for the current versions of each of the web browsers whether it’s supported or not you can see that the let keyword does have wide adoption across all modern web browsers with a couple of exceptions now if you want to go ahead and use the absolute latest version of javascript and then take that second text where you transpile your code so that it’s come backwards compatible with as many versions of the various web browsers as possible then you want to check out a website like anatool actually called babel js so you can find it at babeljs.io and it will again use a combination of techniques to uh to take your code you can see some of this little animation that’s on the page right now you can actually use this to type in some code here and see how it converts it into the older style javascript and i’m not going to cover how to use babel in this course but you should know up front that writing javascript for web browsers requires that you give some careful thought to how your javascript will ultimately be consumed and who your targets are and that definitely means that you’re going to have to take into consideration uh the fact that some people will be using older web browsers writing javascript that will run on a web server using a framework like node.js is a bit easier because well you’re going to have some some upfront knowledge about where that code will ultimately be executed but this is not a course specifically about node.js either even though we’re going to use node.js uh as a as a lightweight means of executing these little tiny javascript examples that we’re going to create throughout this course so you’re going to learn enough about node.js to be able to write a simple tiny application but it won’t do anything cool like serve up a web page however i’m sure there are other courses here on microsoft virtual academy and elsewhere that will help you kind of take that next step so the game plan for this course is to start in the very next video by installing the tools that you’ll need to get started and then we’re going to start with the absolute abcs of javascript and programming in general and i encourage you to follow along by typing in the code that i type in the video and that’s you know typing it yourself is the absolute best way to learn it starts to develop muscle memory you’ll have many of those aha moments where you realize oh i see how these two things are related you can hear it and that’s one thing but to type it in and to see it on your own computer working is something entirely different i highly recommend that you you become an active learner by typing in the code yourself but i encourage you also to pause and rewind the video as many times as you need this isn’t a race you don’t consume these kinds of videos the same way you would watch a tv show a movie or a youtube video if something’s not clear to you don’t just let it go in one ear and out the other and worry and say i’ll figure it out later no stop down and figure it out now because you never know it might be something foundational you’ll need to know uh in the next lesson and the next lesson but by the end of this course you’re going to be well positioned to move on to a more advanced javascript course to learn how to use modern client frameworks like react and view and angular or you’ll be well positioned to learn more about server-side framework libraries frameworks and libraries like node.js and express.js and others but no matter what you’re going to have a great foundation to build on if something i say doesn’t make sense again i can’t stress this enough seek out other sources online and you’re going to ultimately want to know something from me i’ve recorded enough of these courses i know the questions that are already coming you’re going to ask me if there’s a book that goes along with this course that i could recommend and i’m sorry i don’t really have a specific recommendation honestly my recommendation is that you exhaust the dozens if not hundreds of javascript online resources uh where you can simply use them for free and find them in an instant uh if you want to get more explanation about any given idea that are that’s covered in this course okay so let’s go and get started i want to encourage you to take your time don’t feel overwhelmed stick with javascript stick with this course and you’re going to be well rewarded i promise it’ll be more difficult than playing a video game then watching a movie or reading a book but i promise you you’re gonna wind up enjoying it even more than any of those things even if i wasn’t paid to write code i would do it because it’s fun it’s mentally challenging and you get this rush whenever you you write code and you see it working and you’re like wow this is awesome so i’m glad you’re going to get an opportunity to do that it’s the most fun you’re going to have on a computer i promise and you’ll you’ll wind up enjoying it so stick stick with it and i’ll try to encourage you along the way all right so we’ll get started in the next video see you there thanks all right so let’s get started uh we’re going to install the tools that we’re going to need for the remainder of this course fortunately we don’t need a lot and everything is free and everything i show you will work regardle regardless of which operating system you currently have installed so uh regardless of whether you’re using windows mac or linux everything i show you will be available for those platforms the first thing we’re going to need is a web browser i’m pretty sure you already have one of those installed any will do i would probably recommend that you either use microsoft edge or you use uh google chrome the second tool that we’re going to need to install is node it is the the javascript runtime it’s what will actually execute the code that we write and we’ll talk about that more in just a moment and then we’re going to need an authoring tool something where we can actually type the code in now in the past i’ve used notepad to actually demonstrate because i didn’t want to like you know recommend one tool over the other but then microsoft came out with visual studio code it’s available on uh all three platforms so it’s also available for free so no matter what you’re using you should be able to download and follow along now you may already have a favorite tool for creating web pages and so forth feel free to use that i’m not going to do anything that’s so visual studio code specific that it will exclude you please follow along no matter what tool you prefer but let me put in a good plug for visual studio code i’ve been using it pretty much as one of my exclusive tools in my full-time job for the last three months and uh it’s it’s really good so i highly recommend it let’s get started we’re going to need node and you may already have node installed so let’s just see if you do or not let’s go and in windows i’m going to open up a command prompt and i’m going to type in node dash v if i had node installed it would display the version of node that i currently have installed i don’t have node installed on this computer so i get an error message that’s good so to begin we’re going to go to node js i can type there we go nodejs.org and again regardless of which operating system you’re using you should be presented with an opportunity to download either the supported version or the current version which has like the latest features you don’t need that just just use the lts version which is recommended for most users as long as you’re using the version that i’m using or greater we should always be in sync again we’re not going to use any really advanced features of node so this shouldn’t really matter much i’m going to go ahead and run it run the installer here what you see next depending on which operating system you’re using uh will you may see something a little bit different than what i see on screen but hopefully you’ve installed things frequently enough that you can work your way through it so here we have the node js setup wizard and i’ll just walk my way through agree to the license i’m going to pick a place on my hard drive to install this there are some options i’m not going to really do much of anything but i do want to make sure that in windows that this is added to my path this will make sure that node is available in any directory of my hard drive so when i type in node v from anywhere in my command prompt it’ll it’ll pop up okay so just make sure that everything is selected you’ll be fine it’s not that large next i’m going to have to agree to windows uac you might see something different here on the mac or linux i’m going to go ahead and agree to that little security prompt and it only takes a minute or two to install node and then we’ll move on but basically node in a nutshell is uh the v8 javascript engine that they ripped out of chrome they added some tooling around it to support things for like http working with with requests and responses and with the file system and they created one of the most robust web server tools that is available today and many large applications are using node currently to host their applications we’re not going to use it for that we’re going to use it for something much more mundane which is to really just write out little text messages to a console window as we get started then we’ll graduate on and use it in web pages much later in this course all right so i should have it installed right so i come over here and it still says it’s not installed i’m going to have to reboot my computer so let’s pause i’m going to pause the recording of the video right here i’m going to reboot and then when i come back in we should be able to move on from there all right so i’ve rebooted let’s open up a command prompt type in node v and i can see the version number so we’re successful the next step is to install visual studio code visual studio code is different than the full version of visual studio so visual studio community professional or enterprise visual studio code is a lighter weight code editor mainly used for web development but i know people that use it to develop c-sharp applications and other type of of applications where you can uh use the the command line tools to compile your code and things of that nature that’s not something i would ever want to do it’s great for web development and that’s what we’re going to use it for for authoring our javascript files and then executing node commands in a built-in little command window command prompt like we see there again available for all uh operating systems you just go to code.visualstudio.com it should be able to detect which operating system you’re currently using and it gives you a download option for that all right and we’re going to go ahead and run it in place again windows uac prompts me to make sure that i am authorized to install it we get to the to the code setup wizard i’m going to go ahead and accept the agreement and we’re going to work our way through the defaults sure and you can see that we can also add visual studio code to the path which will become available after restart i don’t need that necessarily for this course but hey you know it doesn’t hurt in fact let’s go ahead and use it for everything here that’s up to you you can read those options and choose what you want but for my purposes this will work just great and we’ll see throughout this course some of the things that visual studio code will do for us as we’re typing our our code simple things like uh like code coloring and code completion managing our files giving us an environment to execute command line tools like the node command line tool and there are many things like that intellisense others that will give us the tools to to hopefully allow us to author our javascript code accurately so let’s go ahead and launch it and let’s just do what i call a quick smoke test and we don’t need get for this course i’m just going to hit close on that so what we’ll do is go to the explorer it’s the little icon in the upper left hand corner here let me kind of pull this out and make this a little bit sized a little bit more nicely here i’m going to close down the welcome screen i am going to click open folder and i’m going to go on for me i’m going to go to my c drive and i’m going to create a source folder now depending on your operating system or what your preferences are you may want to create a folder somewhere else but create a folder because we’re going to put some some javascript files and later some html and css files in that folder and we’re going to want a folder structure so right here in the open folder dialog i’m going to right click and select new folder i’m going to call this source lowercase s and source and then select that folder now that becomes the working folder that i’m going to use to add additional files and and all the work that we do for this course inside of there here it doesn’t really wants me to put get install get and i don’t want to do that what i really want to do is go to terminal all right and depending on which operating system isn’t you’re installed on you might see something different here in windows you see powershell doesn’t really matter as long as you get a command prompt and here i’m going to type node v and i can see that that’s awesome and then what i want to do is add a file inside of this folder this working folder so i’m going to click on this little file with the plus symbol in the upper left hand corner i’m going to type in app.js and it opens up a new file here in the main area with a little js icon right next to it and here i’m going to type all lowercase console.log hi i’m gonna go to the end and hit a semicolon so let’s kind of walk through this the word console a period on your keyboard the word log log and then an opening and closing parentheses inside of there i want to put an opening single quote mark and a closing single quote mark and then some word i put hi you could put your first name it it really doesn’t matter but what does matter to me at least is that you end it with a semicolon and as you’re going to come to learn writing code is an exercise in precision if you don’t write exactly what i write there’s a chance that you will not get the results that i get and so you want to double check and make sure there’s not extra spaces you want to double check to make sure that you’re using the right characters like this is not a comma it is the period on the keyboard all right this is not a curly brace it is a parenthesis this is not a double quote although that would be acceptable in this particular situation i would prefer if you use the single quote which is on the same key you just have to hold down the shift key all right to get to it all right so now i’m going to use control s on my keyboard to save or it might be command s if you’re on the mac or something else on linux i don’t know whatever you you use or you can just go file save all right now watch what happens when i just use the space bar on the keyboard did you notice see that little symbol there it went from x to a circle that means that file has not been saved yet that change that i made is not saved so here again i’m going to use the keyboard shortcut to save it then i’ll come back down here into the terminal now how can i do this easily well on windows the keyboard shortcut is control and then the back tick that’s usually next to the number one kind of to the left of it on most keyboards so the back tick will close and open up that little terminal window at the bottom and now i can type in node space and then i want to use the name of this file so app dot js and hit enter on my keyboard and it should print out that word hi that i have inside of those two single quote marks in console.log all right now we can also shorten this up node space app we don’t have to use the file extension and it will work as well all right so assuming that you were able to follow along and you got to this step then you’re ready to move forward and we’re ready to get started actually writing some javascript let’s start that process in the next video we’ll see you there thanks so our job as software developers is to author code which is using a language that’s human readable and author in such a way that can be understood and parsed and interpreted and ultimately then executed by a computer and the code that we write we save into files and we ask we ask some execution environment whether it be a web browser or in this case node to to take a look at this this code that we wrote in this file and to interpret it and to execute it all right and so it’s important first of all as we get started understand that how our code is going to be used we’re working and learning the javascript language but ultimately the code that we write will be executed in let’s be honest one of two maybe even a third environment we’re either going to write javascript code that will ultimately be executed in node and typically when we’re writing code for node-based applications we’re writing applications that we can access the file system access the network respond to http requests and provide an http response things that are more server-side in nature all right and then we’ll also then write javascript code that will execute in the context of a web browser and we would expect for that code to be able to dynamically interact with um with elements html elements on a given web page all right but we might also use javascript to uh to write video games in an environment like unity for example and be able to author and control the various objects on screen and their animation and and their interaction and so on so there’s what i’m trying to get at here is that there’s a difference between the language itself and then the environment that it runs inside of and we need to be aware of that that those are two separate things even though sometimes they feel like one thing in this case console for example the console.log function is provided to us by node it allows us to tell node that we want to print something to the command line like we did just a moment ago now there’s also a console.log function in most web browsers and it allows us to print little debugging messages or console messages that can only be viewed inside of a web browser whenever we have the developer tools open and we’ll see how to do that much later in this course once we start building uh web pages uh and and javascript that can interact with them but at any rate let’s get back to the matter at hand here if i write my javascript incorrectly then the run time what whether it’s node or a web browser will won’t be able to compile it and it’ll give us an error and so javascript is similar to english in so much that javascript has a syntax and it has a proper syntax versus a syntax that’s incorrect so if you’ve ever taken an english english class you’ll know that there are parts of speech that that you’re supposed to use punctuation at the end of a sentence to indicate the end of a complete thought there are nouns and verbs and adjectives and adverbs and and propositions and all these sorts of things right and so you know in general terms the same thing is true with javascript there are parts of speech we’ll talk about those and so you will be learning a new language starting with your abcs and and with with uh i guess uh vocabulary words so to speak and then to move on to authoring sentences that are complete thoughts and then stringing those sentences together into paragraphs in order to accomplish some higher level task and even kind of arranging those paragraphs together to create entire applications all right so hopefully that analogy will serve you well as we get started here our goal as we get started is to author javascript statements and a statement is basically just one complete instruction it’s like a sentence in english and each javascript file that we create like this app.js it’ll it’ll contain one or more javascript statements that will execute in sequential order from top to bottom at least usually and i’ll talk about the exception of that as we get further into this course but there are some other similarities between javascript and english for example there’s an end of line character i was very very specific about adding that semicolon at the end of of our statement and that just is an indication to the compiler that this is a complete thought and it should be carried out as is all right um now we also see that we have our statement all on one line of code and generally speaking as we’re getting started we’re going to write our javascript statements one per line now we’ll bend those rules as some of our statements become very long we can actually for readability’s sake from a human perspective we can split things up onto multiple lines if we need to javascript specifically node doesn’t really care about that that’s really more for human readability it can deal with multiple lines or a single line for a given statement but be that as it may we’re going to try to strive at the beginning to write one statement per line in our files and a statement usually consists of one or more expressions so uh we’ll talk about expressions a little bit later but this particular expression is essentially just executing a function that’s built into node it’s the log function it belongs to an object called console we’ll talk about objects and functions a little bit later here and we execute it by using operators those in this particular case this is the function invocation operator or the method invocation operator it’s those open and closing parentheses and we can even then pass in what are called arguments to those functions so you can see that each little piece of this has a name and it has a role to play in creating our functions and we’ll learn more about that as we move on here one thing to note is that javascript is case sensitive and this trips up a lot of people to begin with that’s why i was very specific to say hey don’t accidentally or mindlessly use capital letters make sure everything is lowercase let’s see what happens if i were to save this work that i did here with the capital c in console and the capital l and log let’s go node space app and hit enter and we get a reference error console is not defined it’s not defined inside of node console doesn’t exist with a capital c inside of node it exists with a lowercase c inside of node the same thing is true with the function name log let’s go ahead and i’ll just use the up arrow on my keyboard that’ll give me the last command that was used in the in the terminal so again node app and i’m going to try to execute this little program again and i get another error this time console.capital l log is not a function that’s true it’s because it’s lowercase l and log and i’ll save that change and then we’ll re-execute this and it will work now there are some things that especially when your application is small don’t matter so you might have accidentally left off that semicolon at the end and the application still runs but that’s a bad practice to rely on that you should always try to create properly formed sentences even though you could write an english sentence or a text message that somebody could understand that has no punctuation has no capital letters and things of that nature that would make it a well-formed english sentence and you’re you’re relying on your the person receiving that text message to understand what you’re trying to say the computer doesn’t work that way it means it needs to know exactly what you’re saying and so you have to be precise precision is the key as a software developer all right so what i want to do here as we kind of start wrapping things up for this first first foray into javascript i’m going to comment out this line and add some new code below it and use that as kind of the next step beyond where we’re at right now so to uh to tell the compiler to ignore line of code i’m going to add a code comment and here i use two forward slashes i added also a space but that was really just for readability’s sake so that myself as a human i can kind of make an easy distinction because sometimes all these characters run together i like adding a space between this but these two characters say forget everything on this line of code don’t compile it don’t try to use it all right and we’ll see in a moment that there’s another way to create code comments as well but here let’s create something a little bit more interesting i’m going to say let x equal 7 i’m going to say let y equal 3 let z equal x plus y and then we’ll do console.log and then i’m going to use open and close parentheses i’m going to use a single quote i’m going to type in the word answer colon space i’m going to go outside of that quote so it’s i’m going to go between the closing single quote and the closing parenthesis and i’m going to make some space for myself in there i’m going to use the plus key or the plus operator and the letter z i’m going to go to the end of the line and use the end of line character the semicolon i’m gonna save it all now before we actually execute this what do you think this will do what do you think will be printed to our console window do you have any guesses i’m betting that your background in math or algebra probably will lead you to the correct answer and i think that your intuition in many cases is something that’s important as you’re learning javascript it is human readable it should be somewhat understandable it might require a little extra explanation because there’s some things that are not extremely obvious but for the most part this shouldn’t blow you away and nothing we cover should ever blow you away it just might require a little extra effort than you’re normally used to putting into things but by no means impossible right so just take some comfort that this is well traveled ground and that if i can understand it i promise you can too let’s run the application see that we get the the the correct result which is answer colon space and the number 10. so how do we get that well we have something here let x and even though again you’re not a javascript developer you know or an advanced javascript developer just yet i’m willing to bet that you understood that we were creating a variable essentially uh a a bucket that could contain a value and immediately we set that variable equal to the value seven and then we did the same thing with the value of 3 we put that into a different variable a different bucket called y and then here we have an expression an expression that will add two values together what are the values inside of those variables x and y well we just assigned them in lines three and four and we know that that probably means we’re going to add those together to get the result of 10 and we assign that into a new bucket a new variable named z and then we merely print out that literal string but then we also say also append the letter or the value that’s in z now hopefully that made sense to you even before we ran the application but you can see here that for example the plus symbol has has double duty it’s it’s serving to be the addition operator but it’s also serving to concatenate two values together in this case to string values together so that we can print it out to screen so we’re going to use this kind of as a starting point and talk about this at more length in the next and subsequent videos but hopefully up to this point you get some comfort level you’re writing some code you’re getting your hands dirty in the code and you know i know you can do this so just keep pushing forward and let’s pick it up in the next video we’ll see you there thanks in this video i want to continue talking about line number three so that we completely come to a full understanding of what variables are in javascript so i’m going to add a new file and i’m going to do that by hovering over the source tab of the explorer and i want to type in variables.js like so and then i’m just going to copy in the code that we had here we’ll use this as a starting point all right so let’s focus in on line number one let’s just first of all let’s make sure this still runs and let’s go node and this time we’re going to give the new file name variables and we get the same result as before great so what is a variable i think i said at the very end of that previous lesson is that a variable is basically just a a an area in the computer’s memory where we’re storing a value we’re requesting or declaring our need for a new variable a space in the computer’s memory where we can put information and retrieve information and then we can from that point on continue to use that variable to to store different values and retrieve those values back out throughout the the life span of the application so there are actually several different parts to the variable declaration statement in line number one the first is the let keyword uh and let’s start start talking about the parts of speech in javascript a keyword is something like let and we’ll see some other examples a little bit later but essentially think of it like a verb in the english language it’s a it’s an instruction to the javascript compiler that we want to do something that we want to take action so we want to create a variable with the name of x and we’re expressing that intent to javascript using the let keyword all right so that’s the first part of it and then the second part is the name of the variable that we want so we’re requesting that a area of storage uh a unit of storage is assigned to our application that where we can put things but how do we reference that again it needs a name so that we can get the values and put new values in memory all right and so that’s usually called an identifier we want to declare a new variable with the identifier of x and we’re going to talk about naming our identifiers naming our variables there’s some rules and some conventions that we need to follow as developers all right we’ll come back to that at the very end of this lesson now before we get too far there’s actually a couple of different ways to to declare a variable in javascript the original keyword that you’ll see used and used in 99 of all tutorials and articles and books and videos is the var keyword and until recently this was the only way that you could declare a variable in the latest version of javascript however the recommendation is to abandon var unless you really need it use the let keyword instead or the const keyword which we’ll talk about in just a moment if we were to save our application using the var keyword in line number one and then rerun it nothing would change so what’s the problem with var there are some well i guess there’s there’s two ways to to kind of explain it at this point the first is that its usage is very nuanced it does stuff that somebody new to javascript may not anticipate the ramifications of until it’s too late and there are problems in code we’ll talk about the var keyword and how it relates to scope and so on uh in an upcoming video but we need to introduce some more concepts before we can get to the point where that discussion is even interesting okay so it’s usage is nuanced and the ramifications can be uh pretty challenging uh if you’re just getting started so that’s why the people who decided what goes into javascript said why don’t we introduce a new keyword called let it will work like most other programming languages as you try to learn javascript hopefully it won’t be problematic so that’s why we have the let keyword the other uh the other keyword for declaring a variable is const and we use that whenever we want to express our intent to the javascript compiler that we do not intend for that variable to ever change its value so what we initialize the value to in this case to seven we wouldn’t expect that to change throughout the lifetime of the application and if we try to change it like in the very next line of code we can attempt to set it equal to six i’ll save that let’s go over and try to run that code we’re going to get an error and it actually is pretty helpful it gives a little a little carrot right underneath the equal sign and it says assignment to constant variable that’s the problem and and the issue here is that we’ve said to javascript we never want to change that value and then the very next line of code we say yeah i’m going to assign it a new value and set it equal to six and it says can’t do that okay so for the most part we’re going to use the let keyword most of the time because that’s the recommendation now in as we learn javascript all right so uh just want to point out that we can uncomment out line number two as we assign the value of x to different values and we can keep doing this as many times we want to so at this point in line number one we’ve declared the variable set it to the seven then we’ve assigned the value of six then five then four we can keep changing the value in the computer’s memory uh and what is the value in line number six what’s x’s value well the last time we assigned a value to it was four so uh the application now whenever we run it will give us seven because three plus four equals seven right so that’s what we get in line number seven great all right so uh i guess this should be obvious at this point the equal sign here is actually what’s called an assignment operator this is how we assign a value into a variable and we can keep assigning values as many times we want but we can only declare value our variable one time so if i were to try and come down here and say let x equals you know seven again or let it equal eight i’m going to get an error whenever i try to run the application the identifier x has already been declared again you can only declare a variable once but you can assign its value as many times as you want to after that all right so in line number one not only are we declaring the variable then we’re also assigning its value right off the bat in the same line of code and when we do that it’s a technique called initialization this is actually two lines of code rolled up into one lines number one and two now are roughly equivalent to what we had before well roughly equivalent there is one difference here at the end of the execution of line number one what is the value of x well let’s let’s find out console.log and we’ll just say what’s the value of x at this point and then let’s run the application and you can see that first value that’s output above what we get now in line number 11 is the term undefined we’ll explain what undefined means in more detail a little bit later but essentially it is what it sounds like we’ve declared a variable but we’ve not defined it we’ve not put a value into it so it’s undefined all right and that’s generally not something we want it might be in some cases something we need uh but for the most part we won’t do that it’s preferable that at the moment of declaration you also in uh initialize your variables if you can alright so that would be valid right there um all right so now let’s finish this up and talk about the rules for naming our variables the variable name itself i think i’ve already referred to this as an identifier and so there are rules for identifier names and then there are some code conventions and these are not enforced by the javascript compiler but are rather things that are best practices as determined by the community of software developers who’ve come before you so let’s talk about those things which are hard and fast rules that will actually break your application rule number one is that all identifiers all variable names have to begin with either a letter a dollar sign or an underscore so that’s rule number one rule number two is that the variable names can contain letters or numbers dollar signs or underscores but no other special characters and you can’t use a space uh in between you know two words that you intend to be considered together as an identifier identifier can’t have any spaces all right and then rule number three is that you can’t use any keywords so i can’t do something like this let let equal to eight maybe if we try that we’re going to get a weird error let is disallowed as a lexically bound name all right and so it even if we were to scroll just a tiny bit it puts that those carrots right underneath the let the second one because we’re trying to use that identifier but it’s already a keyword right so you can’t do that all right so those are your own oh yeah there’s one other rule and that is that variables variable names identifiers are case sensitive so we could do this and it would be a perfectly acceptable application these are two different variables uppercase x and lowercase x so if you intend to do something like this let’s see what we get here all right it doesn’t it doesn’t blow up so we were able to use x and assign it to 8 but we didn’t declare the variable well something fishy is going on and we’ll get to the bottom of it before the end of this course but the key to this is that we did not we’re not working with the same x as we’re working with here all right so let’s just get rid of that but those are the rules has to begin with the letter a dollar sign or underscore the rest of the name can have pretty much anything including numbers but no spaces or other special characters can’t use any keywords for names of variables and uh be aware that uh variable names are case sensitive now there are code conventions and these again are just good practices the first one is that variable names should be descriptive and unfortunately uh x y and z are not very descriptive names ideally we would use something like maybe um let’s go down here so let uh first number equals seven and then let second number equals three and then we could use that in line number 12 instead here’s some better ones actually like if we wanted to capture information or represent information like the first name or let zip code and so on all right so use names that represent the thing you’re trying to store and it from an application perspective what meaning does this variable have inside of our application meaningful variable names the second is camel casing so if you are going to use multiple words you should use this format called camel casing and that means that the first word of your variable name should be lowercase so the f in first is always lowercase but then any subsequent names that we appen or words that we append together should have a capital letter so you can see that i followed this convention every single time in lines 15 through 18. lowercase z and zip code capital c in zip code all right so camel casing third one is to be consistent and that is to always follow the same kind of naming convention and this would be true kind of across not just the names of variable names but for every other type of identifier that we wind up creating in our application stay consistent pick one style and stay with it throughout the remainder of the application and then the other is to not rely on case we’ve already seen the danger of that but what if i intentionally wanted to let zip code equals 60459 what we’ve just done while it’s grammatically correct from javascript’s perspective and those are two separate variables in line 18 and 20. we’ve introduced some subtle um dissonance in the application now it’s more difficult for me to see that these are actually two different variables and maybe i intended to do that but that’s poor programming practice we might choose uh maybe a better name like first zip code and second zip code that might be a better way to go about that same sort of thing okay so those are the code conventions and the naming rules for variables and that’s just about everything you need to know about variables just about there’s actually a little bit more that we need to talk about and we’ll finish up this discussion in the next in the next video when we talk about the values that we’re actually signing into variables and their data types and we’ll talk about that next see you there thanks in this video we’re going to talk about the values that we store in variables and we’re going to talk about the types or rather the data types of those values and why they’re important so to begin with let’s go ahead and create a new file called datatypes.js and this is where we’re going to do all of our work and one of the things that makes javascript so unique when compared to other programming languages is that whenever you declare a variable like we do here let x equal 7 [Music] the variable itself does not have a data type only the values that we store inside the variables have the data type so we kind of see this whenever we’re working with variables we can use something called the type of operator and this will tell us the data type that we’re working with so well let’s go ahead and go back to here let x equals seven so let’s start off by just doing console.log and then we’ll say type of all one word lowercase and then x and let’s save that save it and uh here i’m going to type node and then data types and you’ll see that it outputs a number so that’s one of the first data types the x data type is a number and a data type is really just the kind of data that we want to store so if you want to perform math or some algebraic operation then you want to use a number and if you want to do a yes or no true or false uh evaluation then you’ll want to use a boolean and if you want to display something on screen then you’ll want to use a string which is basically a shorthand for string of characters and you usually represent those with single quotes with whatever string of characters you want to uh to use inside of it so let me give you a few examples here we’ve already looked at number let y equal true and so then we’ll do console.log type of y and then i’ll just go ahead and do z as well let z equals hello world and then console.log z whoops not to z i want type of z all right and so now let’s go ahead and run this and we can see that we get the three data types that we’re currently working with a number a boolean and a string so in the case of a number it can be any positive or negative number it can even have decimal values in the case of a boolean it can either be true or it can be false those are the only two values and then if we want to create a string it’s going to be anything inside of the single quotes it’s a literal string of characters but i literally want h-e-l-l-o space w-o-r-l-d all right and so those are your three of your seven basic um basic types data types there’s also another case let’s let a and then console.log the value of a and then console.log type of a all right and just to remove the confusion here i’m going to use a multi-line comment this allows me to avoid having to do this on every line right i can just do this little slash star at the top then go down to the bottom of where i want to comment out and then star slash you can see everything that’s highlighted in green or or turned to the green color is now commented out just as if i had commented out each individual line separately so here i’m just creating a variable a but i’m not initializing it to a value remember we saw do you remember what it output when we did this before it output the value undefined but we want to see what the type is because we said that it’s the the value that’s assigned to the variable that has a type so what is the type of a variable that has nothing assigned to it well that’s what we’re going to get to the bottom of right now so we see that the value is undefined and the type is undefined so now we have four types we have number boolean string and undefined and there’s two or three others that we’re going to look at here before the uh before the very end we’ll get to them they’re a little bit more complex but those are the four that we have to work with at least to start off with and so that’s all i really wanted to say the next thing we’re going to talk about very quickly is how i would convert one type into another type how do i force javascript to treat a string like this console.log and then a literal string of the value nine how do i make it treat it like the number nine well we’ll talk about that in the next video we’ll see there thanks in the previous video we learned that values not variables have a data type and that the data type is essentially a description of what you want to do with the data there’s more to it than that but for our purposes right now it’s essentially what we intend to do with the data and we learned of four data types and we’ll learn about a couple more a little bit later there’s the number data type the string the bool and the undefined so let me ask you this what happens when we need to use them together and they don’t quite work the way that we think they should what options do we have then so let’s go ahead and create a new file i’m going to call this coercion c-o-e-r-c-i-o-n dot js i think that’s how you spell it and uh let’s start off with a quick little example here so let a equal seven let b equals the string the literal string so i want to use single quote 6 single quote all right and then let c equals a plus b and then console.log answer and then c all right before we execute this application what do you think is going to be output uh when we run it what will the answer be all right get that in your mind and now let’s go node and coercion and uh looks like we don’t get anything at all oh i need to save it okay there we go let’s try that again there we go we get the answer 7 6. wait 7 plus 6 should be 13 right why are we getting 76 something i can see what’s happening it’s not treating these as to numeric values it’s treating them both as string values so it’s not adding two numbers together somehow it’s coercing that a from a string in from an integer into a string and then concatenating together a and b so this operator the plus operator we saw how we can use it for addition but we also it plays double duty and it’s the string concatenation operator but moreover javascript realizes that it can’t add a a number and a string those are it’s like adding you know an apple and a car together it’s not like making an apple and an orange even these it’s not like fruit salad it’s like two disparately different things what do i do well i will i will take the numeric value and coerce it convince it force it against its will to become a string and then i will concatenate the two together so that’s the notion of coercion and most people consider that to be an evil thing or a very dangerous thing and others just say well it’s just what happens you know it’s just part of the language now what if i really wanted to perform addition on two integers well then i would need to take steps to force the string six to become a number so that i could then add them together and so to do that there’s actually a special function that will force that conversion so let me uh change this just a little bit and um we already have the value b so i’ll just reuse the value b and i’ll set b equal to parse int now i want you to notice something i haven’t really talked about visual studio code much but one of the nice things about visual studio code is that it popped up this little box called intellisense and intellisense is just a visual cue as i’m typing to show me things that i might need to reference or things that will help me to to find the right command or the right idea in this case i knew it was something parse so i start typing in and i can then use the arrow keys to start looking i’m like oh yeah there’s po parse float that would give me a number with decimal values but this in this case the the string that i want to use i know that it will only be a value without without any decimal point so i want to use the parse int now what i can do is just use the space bar or like the opening parenthesis whatever the next logical character is to do what’s called code completion so i don’t have to type everything else now in this case i know that i’m going to need to use the parentheses for reasons i’ll talk about later so i’m just going to do an open parenthesis well it didn’t do it for me well there we let’s just go ahead and [Music] use the tab key instead all right so the tab key will give me what i want now i’m inside the the parentheses that i need to pass in first of all the string that i want to change so in this case take the value of b and then i need to give it optionally what’s called a radix or radix and that is essentially the base system so if i wanted to um to use like a hexadecimal i might give 6 but in this case i’m going to give it 10 because i want to be a base 10 or a decimal conversion all right so that’s a little technical but typically if we use 10 in there we’re going to be just fine so essentially what i want to do is take this 6 and based on the normal decimal system i want to convert that into a numeric value and then i want to continue on in lines four and five like we had before let’s see what we get this time the answer is 13 just as we had hoped all right so the parseint is a built-in function to javascript and i can count on it being available in node or in a web browser or any other implementation of javascript all right so i guess this begs the question what if i try to do something kind of evil with this so let d equal uh parse int and then i’ll use the tab key to do the code completion and this time i’m going to pass in a character that will not convert to a or or even a string that will not convert into a numeric value especially one that’s decimal so i’m going to save this well let’s go ahead and console.log it and d so let’s go that and then we’ll do this all right and i get n a n which represents not a number it’s not really an error it’s just telling us that the value we passed in is not a number um we could actually do something along these lines as well um let e equals is n a n and then i can give it some numeric value in this case i’ll give a d and i’ll do console.log e so let’s save that run it again and so this time now i’m evaluating whether d is not a number and that is true it is not a number because i can see it here that’s printed out all right so we saw two built-in functions but there’s a bunch of built-in functions for various things all kind of centered around in this case just working with coercion and checking the results of that attempt to to coerce or or convert one data type into another all right unfortunately there’s no parse boolean so you can’t take a string of true or false and convert it into a boolean you’ll have to take a few extra steps there’s a bunch of of examples online for that and so depending on the type of conversion that you’re attempting to to perform it may not be easy to convert from one to the other there’s always a way and usually you can find some code online especially on a site like stack overflow that will help you figure that out but that’s all i wanted to say let’s continue on the next video we’ll see you there thanks in this video i want to refocus on the javascript syntax specifically and the various parts of speech inside of a properly formed statement in javascript so i started by explaining javascript by saying that you write statements each of which are executed sequentially and statements are complete thoughts complete instructions to the javascript compiler of what we want it to do for us and i said the statements are made up of one or more expressions and that an expression is made up of operators and operands and i just made that statement in passing and kind of blew past it really quickly but i wanted to take a few moments and explain why that is an important statement whenever we’re setting out to write code and so we’ve already looked at a couple of different operators if we’re thinking about the most atomic level of our javascript statements we’re thinking about in terms of operators and operands so operators are things like keywords we’ve already looked at the addition operator using the plus symbol we looked at the string concatenation operator using the plus symbol so that one is doing double duty and it will be understood based on the context of how it’s being used and then there’s the assignment operator the equal sign that we’ve already looked at and soon we’re going to look at a few other common ones just to start building out a list of operators that we can use to do more interesting things inside of our application but there’s also an operand so operators are things like keywords and those various symbols that we’ve already looked at and we’ll add more operands are something like identifiers a variable name we’ll we’ll learn about functions soon and functions are another type of operand and so unlike keywords and operators in javascript which are fixed and part of the language we you and i programmers give operands their name and so by combining operators and operands we create expressions that are then used to compose statements and so sometimes it’s easy to spot an expression and then sometimes it’s not so easy but identifying several major categories of expressions we can better understand why javascript works sometimes and why it doesn’t work sometimes so for example in the english language we cannot write a sentence a proper sentence like this the dog period if we’ve said hey uh the dog some our friend would say what are you talking about the dog did what which dog you know give me some more information right why is that not a proper sentence in english because it didn’t have enough inside of it to be considered uh proper we have a noun we have the dog but we don’t have any verbs or adjectives or adverbs describing or or um you know kind of giving us more detail about the dog the same thing is true with javascript so we can’t for example let me just create a quick file here we’ll call this expressions.js so we cannot do something like this in our program right uh because the javascript compiler will say okay what do you want me to do with that uh that makes no sense to me whatsoever i don’t know what you want me to do with a i don’t see it it’s not one of my variables you’re not asking me to create a new variable there’s nothing inside of a a means nothing to me all right so at a minimum we’re going to need to either and these are the types of expressions in a very high level we’re going to either declare a variable so we would do something like this once again let a all right and even in this little tiny um two word line of code there’s already an operator and an operand here’s the operator the let keyword and here’s the operand a name we want to give to a new variable that will be created in memory all right so that’s one type of expression we’re going to call this types of expression here we’ll just use some comments types of expressions [Music] number one variable declaration i think i spelled that right all right so let’s go ahead and just move that up to the very top and say this is bad uh and then we’ll do something like this i kind of like doing some ascii art there whenever i create lists inside of my code all right so there we go the other one is to assign a value so the other type of expression we can assign a value so a equals three or four uh and then another type of expression is to perform an evaluation that returns a single value and so that might be something like and if we’re talking purely about the expression itself it might be something like that b plus c so in a more interesting example uh we might do something along these lines um and i’ll just comment this out because i want to reuse a there we go good all right so here we go line number 16 i’m going to go let b equals 3 let c equal 2 and then let a equal b plus c i just want to focus on line number 19 and i want to say that there are three expressions in here can you find them all right well let’s identify them so number one we’re gonna see that uh let a so that’s a variable declaration the next thing that’s going to happen is we’re going to perform an evaluation of b plus c right and that will basically add those two values together because we’re using the addition operator and then finally we’ll do um the result of b plus c is assigned to a so three expressions all combined into a single statement and there’s a lot more going on than meets the eye but that is the kind of thinking that will help you understand why your javascript code works sometimes and sometimes it doesn’t you have to think in terms of writing expressions that do things to form properly formed javascript statements all right so hopefully that little lesson in syntax is helpful let’s talk about operators and the different types of operators and again we’ve used this collection of five or six operators so far let’s let’s add to that collection i’m gonna go create a new file called operators dot js [Music] and so um there are several categories [Music] of operators and i’ll just kind of go through them really quickly here so there’s assignment like the equal sign it’s really the only one in this category but it’s a pretty important one we’ve seen it use quite a bit there’s maybe some other keywords and things that can fall into this category sort of but the assignment operator is usually the only one in this category and there’s arithmetic with which as you might uh suppose would allow you to do mathematical style operations so that’s the plus where we’re adding two numbers together subtraction multiplication that’s the asterisk key over the eight on most keyboards um there’s also the division all right and then there are some special ones like um let’s call these and i’ll they’re kind of arithmetic but i’m gonna call them increment decrement so this is the plus plus and the minus minus and used out of context these don’t seem so interesting but what we could do is for example um let’s go var a equals one a plus plus and then console.log a all right let’s save that and then go over to our terminal and i’m going to do node operators all right and so you can see that we increment the value of a so let’s do this let’s now increment it one more time and see and let’s save our work here and then let’s run it again and wait a second the value is still two how is that possible let’s do this console log a like that so now we’re going to print the value out twice we’re going to print it out i thought maybe we would get three but we didn’t but if we print it out a second time let’s see what value we get and so when we print it out the second time we get three and the reason is this because this operator this increment operator works after the line or after the value is already utilized inside of this line of code so basically hey console.log here’s a and after you print that to screen then let’s add something to it that’s why we’re able to see the new value if i print it a second time all right what we may have preferred instead of this is to go console.log and put the plus plus before the a that means i want you to first evaluate the increment of a and then print it to the console.log all right so let’s save that let’s rerun this and now we see three in both cases the same would be true with the decrement where we could subtract either before or after the evaluation of that variable all right just something to keep in mind all right so that’s increment and decrement um there’s also going back to arithmetic there’s the modulus and this will give me uh the the remainder amount so let’s go var m for modulus equals 10 divided by whoops whoops whoops that’s not what i wanted 10 modulus 3 and then i want to console.log m and just to kind of keep everything clean i’m going to comment out all this as well keep it around for posterity but otherwise that’s all i want to see what will i get back from this this statement and i get one what is one it’s the remainder so 10 divided by three equals three with one left over that one is the modulus all right and actually this becomes a lot more interesting and important when we’re looping through lots of values and every like 10th or 20th or 100th item i want to print a little message to screen to say hey we finished processing the the 10th the 20th the 30th the 40th the 50th item all right and i use that actually frequently so i’m a pretty big fan of modulus let’s comment that out so uh moving on to the different categories of operators uh let’s talk about the various string operators and we’ve already seen these so this is going to be like the literal string operator we’re using single quotes and then also we saw the string concatenation operator that will take two strings and and allow them to be appended together to create one new string other operators precedence so we might uh you know order of operations we actually use this quite a bit um even in non-mathematical situations so for example um let’s just do var b equals 1 plus 2 times 3. now if you’re coming from an algebra background there’s an order of operations where things should be done in a certain order and i’m pretty sure if memory serves me correctly it’s been a long time since i’ve had an algebra course but you perform algebra before you perform addition so if i were to do a console.log here i would expect b to output two times three plus one so that would be seven let’s see if my my memory serves me correctly here and yes it does but what if that’s not what i want well i can use just like in algebra i can use parentheses to kind of control the order in which things are evaluated so in this case i would do 1 plus 2 first and then multiply that by 3 which will give me a completely different result of nine because three times three equals nine okay so we’ll use this uh the um the opening and closing parentheses for different purposes uh for example um whenever we want to do console.log these parentheses are also used as the um the function invocation operators all right and that just says here’s a function name called log and we’ll learn about functions soon but i want to actually invoke the function now and i can even use the function invocation operators the opening close parentheses to pass in arguments we’ll talk about that a little bit later but again that is the open and closed parentheses um there are other operators and i’ll just put them here they may not make a lot of sense at the moment but they will soon when we look at decision statements so there’s the logical if i’m sorry the logical and in the logical or okay so when i want to add two things together and evaluate two things together either one of them needs to be true or both of them needs to be true and we’ll look at that in in a little while there’s also the member accessor operator so when we did console dot log if you look at intellisense as i hit the dot on the keyboard there’s that period why are we using a period there that allows me to access the various members of this object and we’ll talk about object and we’ll talk about properties and functions or methods of objects soon but that’s what allows me to access the log function of the console object inside of javascript so here again comment that out but we’ll use the period for that purpose we’re going to also look at the code block operator soon and so you know i’m going through all these i’m saying hey we’ll look at these soon really the point of this exercise is to say that there’s lots of operators and we’re going to have to begin to identify what all these special characters are and the only way to do that is to first of all learn that they exist what their function is and then use them as we’re writing programs and so i think that’s really the only thing i wanted to say i mean let me just put one more in here the array element access operator goes by different names but i’m just going to use that and so we’ll use square brackets for that purpose so almost every single character the special characters that are above our numeric values and we can access using the shift key and the various ones that are usually on the right hand side of the keyboard the various braces and brackets and colons and semicolons and and all these are are are used to um for various purposes in javascript uh and in most programming languages all right so i think that’s all i really want to say uh let’s pick back up in the next video you’re doing great hang in there with me we’re getting through uh some of the easy stuff and we’re gonna start moving on to some challenging stuff here really quick but you’re doing great see you in the next video thanks up till now each variable that we create can store one value at a time per variable but what if we need to work with lists of data in other words i need to keep track of several people or several numbers and i need to store them in such a way that it doesn’t matter if i have 2 or 10 or 100 i can kind of keep them together and move them all around and use them in my application as a list as a grouping of related values in that case i want to create an array and so let’s start by creating a file called arrays dot js and first of all it’s basically an array is basically a variable that can hold many different values and so we can declare variable and initialize its value like so so here we’ll do let a equals and here we’re going to use an opening and closing square brace or bracket and then i’m going to give it a series of values each value will be separated by a comma for 8 let’s say 15 16 23 and 42 all right and so now i have an array of those values now these are just numeric values what if i wanted to create an array of string values i can do something similar in fact i can use any data type inside of here that’s allowable in javascript and we’ll see some examples of that a little bit later but i might want david eddie alex and michael all right and then what if i want to get one of the the values i can just do console.log all right inside of here i’m going to use the variable name so in this case i’ll use a and then i want to provide a index to retrieve one of the elements so each of these is an element of the array and i want to use an index a numeric value that that allows me to get at one of those elements inside of the array the indexes are zero base that trips up beginners sometimes uh you for example to get at the number four the first element in the array i would use the index zero if i want the second item in the array the second element of the array i would need to use the index one and so on so to get at it i’m going to use a and then right next to the a square brackets and then i’m going to give it an index so here we’ll grab the first value and then i’ll grab the second value and then i want to do show you how console.log will just print out all of the values for you nicely if you just want to give it the name of the of the array itself the the variable itself so let’s save our work and um we’ll go node arrays all right so you can see the first element of the array at index 0 gives us the value 4. the second element of the array at index one gives us the value eight all right hope you can see the correlation there or if i just want to print out all the values in the array i can just provide the variable name that contains the array and it will print them all off for me just like i have kind of here when i actually initialized our array variable all right let’s comment this out now that is how we access individual elements what if i wanted to change or set the value of one of the elements the same would work so in this case i would say for example a0 and i would set it equal to 7 like so and so then we can just do console.log like so and then we run our application now you see the first element of the array has been changed from 4 to 7 because that’s how we can access a single element and assign it a new value all right all right so um what about these mysterious uh these mysterious arrays what is their data type so let’s do console.log type of a and [Music] we can see that it’s of type object and we’ll talk about the object data type later because there’s a lot more to it than just being able to create arrays but it’s a little bit more advanced at this point we’ll get into it soon just keep in mind that an array isn’t a data type of itself it is a type of something called object and we’ll talk about objects later all right um so the other thing that’s important to remember is that a array can can include elements of different data types so let me just do let c equals um [Music] we’ll start it with four and then we’ll do alex and then we’ll do true all right so we’ve used three different data types right there and we can just do uh node arrays oh i need to actually do a console.log c there we go there we go all right so you can see that a single array can hold different data types there’s no restriction there let’s comment that out what happens if i try to access an element that within with a index that does not exist so let’s do console.log and i happen to know that the b has four different elements in it four names and let me try to access the fifth element by using the index four and this will be undefined so just like a variable without any value assigned to it is undefined so is a element of an array undefined if we don’t give it a value now i can also just programmatically determine the number of elements in an array by using a special property called length so i can do console.log a dot and remember the dot is the member access operator so arrays are objects and this particular object has a special property called length which will give me the number of elements in that array so i would expect to see let’s see one two three four five six so the question is is it going to give us six the actual number uh or is it going to give it us to it in a zero based fashion and the answer to that is that it will give us the actual number not zero based and this will come into uh into play a little bit later when we use the length of an array and we uh iterate through each element of the array to print them to screen when we learn about looping all right so just keep that in the back your mind now there’s a lot of strange things that you can do with with arrays and some of them are not always intuitive like for example if i wanted to just randomly create a new element so in this case i’m going to create what the um use the index 10 which means this would add an 11th element to the array what happens with all of the elements between where we left off 0 1 2 3 4 5. so 6 through 11 what will we get so let’s just assign this to 77 and then i want to do a console.log of a and then i want to do a console.log and a dot length like we just learned about and kind of see what happens here and then let’s run that all right so we can see that it prints out four five six seven or i’m sorry 4 8 15 16 23 42 and then it says there’s four empty items and then there’s 77 and it says that there’s 11 uh there’s 11 items 11 elements in this array because we filled up the 10th index or index 10 with a value so it will create essentially what’s called a sparse array and that means that there are empty elements inside now this isn’t usually the way that you want to work with arrays if you need to add new values because it’s not as safe we’re inadvertently creating elements with nothing in them there’s a safer way to go about this using some additional built-in functions of the array and so if i wanted to add that value and add it to the end of the array no matter how many elements are currently in the array i could use the push method and so i say hey i want to push the number 77 to the end of the existing array so let’s um let’s copy this and paste it here and then if i wanted to remove it i can use a method called pop so this function pop will remove the last element of the array in fact i can call it several times to keep removing elements of the array and here we’ll just print out what the end result is just like we did previously so now this should put some fireworks into our terminal window so you can see that using push in line number 29 i was able to add the number 77 to the end of the existing array and that gives me seven total elements now i call pop three times it removes 77 42 and 23 leaving us with just four elements in our array okay so we’re going to continue to use arrays they’re a great way to to keep lists of things together and accessible and will become even more important again as we learn how to loop through arrays and to evaluate each element we can even use arrays to hold on to other things like like objects and functions and we’ll learn about some advanced use cases uh with arrays a little bit later all right so that’s all i have to say about arrays let’s move on and start looking into some things that are beyond the absolute basics we’ll start moving and talking about functions all right see you there thanks throughout this course even from the very first line of code that we wrote we use the console.log function to print things to our terminal window and i kept referring to log as a function as part of the console object in its simplest form a function is merely a block of code that we as programmers can name and once it has a name then we can call it by its name but it’s just one or more lines of code that we put into a block and then we say we want to execute that block over and over and over again throughout our application so again that’s a very basic explanation of what a function is but in javascript function functions can do so much more in fact most of this course will be devoted to working with functions because frankly they’re one of the primary constructs in javascript for getting things done so first of all uh let’s go ahead and create a new file i’m going to call this function declarations.js all right and first of all if i have some code that i want to reuse throughout my application i want to add it to a function so we can create a function and i’ll walk through and explain the parts of a function here in just a moment let’s create the most basic function that i can possibly think of and i’m actually going to copy and paste some code in so we don’t have to type at all but nothing here should be all that revolutionary so i’ve created a new function called say hello notice my name i use camel casing right in order to name my identifier my function name all right and then i have three lines of code notice that they’re inside of these curly braces notice that they’re indented so we see kind of a relationship between this code on the inside and this line of code and this line of code on the outside so it kind of represents a container relationship this code sits inside of or is part of or is rather the body of the function that we’ve just declared all right so um here we just declared a simple function this is called a function declaration this style we’re going to look at other ways to define functions later and i’ll draw your attention and why you’d want to choose one or the other later there’s at least two other ways that i’m thinking of off the top of my head but first of all notice that we use a keyword call function then we give the function some identifier that we come up with something meaningful we’ll use similar rules to what we use for variable names all right then we use an open and close parentheses you’ll see how these will be used a little bit to define arguments or input parameters to our function but right now it’s empty we don’t require that the caller give us any additional information uh and then we use the open curly brace here and the closed curly brace here to define the container to define the code that we want to be the body of this function and everything inside of that is just any javascript that we want to write for the most part all right so uh how do we actually then use this well we gave this block of code as defined by the open close curly brace we gave it a name and so we should be able to call it by its name so i should be able to do something like this right say hello and that will get me most of the way there but to actually invoke a function we have to use the function invocation operator in this case it’s the opening close parentheses and obviously we want to use our end of line statement here so let’s go uh node and then function declaration [Music] and let’s see oh declaration sorry there we go all right and we get hello so hopefully you weren’t expecting something uh super interesting we’re just printing out three lines with what i would call a flower box kind of a rounded some dashes to to style it up a little bit we can do some interesting things with regards to assigning the function to a variable so let’s do let a equals say hello now do i want to invoke the function here no and i’ll explain why in a little bit i merely want to get a reference to the function and then i’ll do um a and invoke the variable so this variable is now pointing to this function and now i say okay i have a function inside of this variable go invoke it using the function invocation operators in fact here let’s do it a bunch of times just to make sure that we’re seeing what we think we should see here and so we can see hello hello hello all three times in a row great so let’s comment that out now up to now this function’s not all that interesting let me just copy it and i’m going to comment it out and i’ll create a new version of this function down here beginning in line 17 and i want to actually pass allow me to pass in a name so i can say hello bob hello steve right so we’ll just create a new argument into our function say hello by giving it a variable name so essentially now we’re able to use this variable name in the body and we expect the caller to give us the name it wants us to say hello to so um here i’m just going to use some string operators here with name and make sure things are spaced nicely and so here i can do whoops say hello to bob [Music] say hello to beth say hello to mr tibbles my cat all right and let’s go ahead and run it and you can see now how i’m able to reuse that code but change it up by passing in the name that i wanted to say hello to all right so let’s comment all this out and let’s talk about one more thing that we can do with functions and that has returned values from functions so this first uh function that we created it’s merely just outputting we’re not expecting it to to perform some operation and then give us some value back but what if i wanted to create a more interesting function that implements some business rule in my system and my e-commerce system like to calculate the sales tax on a given amount say a subtotal of all the items that are in my shopping cart i might create a simple function called um calculate tax like so and we’ll get to the body in just a moment but i want to allow the caller to pass in the amount that we’re going to charge tax to all right then i’m going to say let result just the name of a variable result be the amount that value passed in times [Music] 0.0825 which is the sales tax where i live and then i want to use the keyword return and then the value i want to return so you can return one value from a function in this case i want to return the amount of tax so i’m going to return result now what i’ll do is i’m going to call calculate tax passing in an amount so let’s say a hundred dollars and i want to capture that into a variable i know it’s going to return a value to me so let’s just do let and i can reuse the variable word result but i might use something more descriptive like let tax equal calculate tax and then console.log the amount of tax like so let’s save that and then let’s run it and you can see that for a hundred dollar purchase it would charge eight dollars and 25 cents in tax okay but that’s what the purpose of the return keyword is to actually give me back something so this is an expression a function invocation expression it’s going to give me a value back that i can then assign to the new variable tax and then i can work with that that value in this case a uh a number representing the amount of tax all right and i think that’s all that i’m going to say about this for now but there’s lots to say about functions it’s going to again consume the majority of this course and you’re going to have to become very familiar with the ins and outs of working with functions and we’ll start that process in the next video we’ll see there thanks in the previous video we learned how to create a function declaration and a function declaration and a variable declaration are similar in so much that they both have an identifier or a name because we plan to call them later on in our javascript but what if we don’t need a name what if we’re in a situation where there’s just a need for a function but that function will never get called for the rest of the application we know that then we can take a different tact we don’t need to add a new identifier we can just create what’s called a function expression and we don’t have to supply a name we just give it the body of the function and say here go do this when you need to run some code all right and a good explanati a good use of that is whenever we need to create some code that should run in the future so here let me start off by creating function expressions.js a new file and here i want to use the settimeout method that’s available inside of javascript and if we use intellisense we can see that there’s actually two input parameters to this function set timeout we’re going to first of all need to give it something called a handler which i happen to know is just a function now i could give it a function declaration but usually people just create function expressions here for the handler and then the second thing we’ll need to do and i’ll use the down arrow to move from the first argument to the second argument is to give it a timeout and so that’s the number of milliseconds that i want it to wait before executing this code and i’ll show you how that might be interesting in just a few moments here but the first thing we need to do is create a function expression to pass in so just here right in line i’m going to create a function open close parentheses open close curly braces which denote the body of this expression i’m creating inside of here i’m gonna do something simple like console.log i waited two seconds and then here at the very end of the function declaration i’m going to give it that second argument the number of milliseconds that i want to wait before executing that function that function expression so i’m going to say wait two seconds and then i want you to call this inline function i’m creating and the body of it will merely just log out i waited two seconds all right so here we go let’s go and uh do node and then function expressions one one thousand two one thousand and you can see it prints to screen i waited two seconds all right now it’s kind of hard to read it like this all in line one of the things in javascript that’s a little bit challenging especially if you’re getting started is the number of curly braces that you’ll encounter and differentiating for example this outer set of parentheses and this inner set of parentheses and and visual studio code tries to help you like when i put my carrot right next to that opening curly brace it tries to find the matching closing curly brace and you’ll see as we add more curly braces for different purposes and indentation levels inside of our application visual studio code does a pretty good job most of the time of finding its match it’s just a matter of looking for that carrot that surrounds the closing one here over you can see whatever in column number 61 here i’m looking at the the bottom okay anything inside is just the body of the function and the same rules apply whoops i didn’t use a semicolon at the end of that line but i should have all right it shouldn’t change the function in this simple case but nothing changes about how we work with this now to be honest most people do not put this much code on a single line i may want to split this up into multiple lines so i would do this in a way that feels natural to me and you can see that as i put my mouse cursor next to where i feel like the split should have been like at the beginning of console.log and here at the end of our body of our function expression visual studio code naturally will create some indentation now if i don’t like that level of indentation i’m free to come in here and change it up like i would prefer to use a tab here so i’m using the tab key on my keyboard to move things out and the shift tab to move things back that only works if my mouse cursor is here right at the beginning of that line if i were to move one character in and use the tab key well that’s you know that’s not what i want at all that’s going to split that word up but if i use the keyboard the arrows on the keyboard to maneuver and then the shift tab to move it out i can move things in and out but that is pretty much how i would like to see that function represented right and then i use a comma to pass in a second argument in this case the number of milliseconds to my set timeout function all right so but the f the the focus of this is that function expression i never want to use that function again but i need it in this case as an argument to pass into my settimeout function all right so functions can take functions as input parameters okay so uh just keep that in mind because things are going to get a lot crazier than that and let’s move on and talk about using both the function declaration and a function expression to do something just a little bit more interesting here same basic idea here but what i want to do is start off with a counter and this will count the number of times that we actually execute our uh our function expression i’m going to start with a function on the outside function timeout let’s call this function timeout like so and then inside i’m going to set timeout using that built-in function to javascript and pass in a new function expression all right and then i’m going to here give set timeout say in two seconds i want you to basically run this function expression that i’ve defined right there so i pass in the second argument of 2000 again you using visual studio code to help me find the matching set of parentheses at the beginning and the end to pass in uh the uh input parameter to the set timeout function recognizing that the function expression is the first argument to that and 2000 is the second input parameter to that set timeout function here’s what i’m going to do now i’m going to append so i’m going to put a little space there between high and the closing single quote mark counter but i want to after every time i reference calendar i want to increment it by one so this will allow me to count the number of times that set timeout has run now one of the things that i want to do is after i have printed that line i’m going to schedule the next time that this code should run so i’m going to schedule and call timeout in a recursive manner so i’m using the name of this outermost function and saying hey uh now that you’ve run me run me again in two seconds because i’m gonna basically call set timeout again all right now i need to kick this off the first time so we’ll call set timeout once here on line number 15. and that will kick things off and then [Music] i’m going to hit ctrl and c on my keyboard to stop the execution because it’ll just keep looping and looping and looping all right hopefully in your mind you understand the sequence of events here i’m going to call this function declaration once the body of that function will create a set timeout in two seconds i want to execute this function expression which will not only show me the number of times that this function has been called because i’m keeping count of it in that counter variable but then also it’s going to call the timeout function again which will schedule two seconds from now the next call to the set timeout function okay so let’s see it run this all makes sense so i waited two seconds saw it run once all right twice three times and see it’ll just keep going every two seconds until i hit ctrl c on my keyboard to stop its execution all right all right the last thing that i want to show you now comment all this out is that you can create a function declaration i’m sorry a function expression that says something like console.log and i’ll make something a little bit more interesting later and then i can immediately invoke that function by first of all surrounding this function expression in parentheses just kind of say hey i want to group all this together and then using another set of parentheses as the function invocation operator like that do you see that format so there’s this intersect that we use just to define input parameters we don’t need any but we still need it in order to create a function expression then we’re going to group this whole thing together and say i want to execute it so there’s actually what four sets of parentheses we just have to keep them straight in our mind on what each of them are doing but this last set will do what’s called and this kind of structure is called an immediately invoked function expression in other words i will have a function expression and i want it to be invoked i invoked immediately when this application is run and this actually is a pretty common pattern in javascript development it comes in super handy and we’ll talk about why it comes in handy a little bit later but we want to just remember immediately invoked function expression it’s also just known as an iife sometimes i think it’s pronounced iffy all right so keep in mind if these and we’ll come back to them a little bit later all right so let’s move on and uh move away from functions just for a little bit we’ll come back to them later uh but hopefully you can now tell the difference between a function declaration of function expression most importantly for our purposes you want to keep in mind what immediately invoked function expressions are okay all right so we’ll come back to this and uh let’s move on see the next video thanks in this video we’re going to talk about decision statements there’s actually three that we’re going to consider the if the switch and a ternary operator and so whenever we need to add logic to our application in other words perform different blocks of code based on some condition that we evaluate we’ll want to use one of these decision statements and so let’s go ahead and start by creating a new file called decisions.js and here what we’ll do is start with the if statement so the basic structure looks like this if and then we’ll evaluate something here some expression so let me just kind of start off with this some expression that expression should equal true or false and there’s lots of ways to evaluate this we’ll come back to it in just a moment but we’ll consider those in between the opening and closing parentheses if that is true whatever that expression is then we’ll execute all the code inside so let’s begin simple bar count equals three we’ll just hard code a value and then say um [Music] so if count and then we’ll use the equality operator so this is going to evaluate for equality if count indeed is equal to 4 then we will that will that expression will return true if it’s true then we’ll perform whatever code we write here so console.log and count is four so the first time we run this we’re not going to get really anything all right so the first time we run this we’re going to not give anything it’ll just exit what we can do is change this to count equals three like so and now when we run it we’ll see the message count is three all right very uninspiring let’s set this back to four and here we can consider the alternative that the count is not equal to four and we could kind of give the counter message count is not for this much we know to be true all right all right so count is not four we basically skipped over this block of code because this returned false therefore we executed the else statement this second block of code and skipped over the first one okay so there’s actually several different variations of this we can use because there are some different conditions here maybe i don’t want to jump right to that else statement maybe i want to keep evaluating i can use an else if and so here i might say else if the count is greater than four then i could maybe do a message like console dot log uh count is greater than four and i can do kind of the opposite as well else if count is less than four so console.log count is uh less than four i guess i changed modalities there and then at that point this will never happen ever because one of these three conditions would occur we’d never get to this final else statement right it would just would never happen so it’s going to save our work here and see this run count is less than four because it’s three okay so that’s the general structure of the if statement it allows us to evaluate one or more expressions if it returns if that expression returns a true then we execute the code in the code block associated with that expression we can create optional else or else if statements to continue to evaluate other expressions usually you’ll want to make related ones but you don’t necessarily have to although that may not make a whole lot of sense depending on your business rules and then we can finally use a catch-all in case none of the previous else if statements uh are are correct and kind of capture that so let’s go ahead and comment that out that’s our first structure we’ll use the if statement a lot the next type of statement is a switch it’s a little bit more tricky to use let’s start off with just typing out the switch keyword and what we want to evaluate and so what we’ll do is actually evaluate whatever’s in this expression against a number of cases so i might for example let hero equal superman and then depending on the hero i might want to print out the um the super powers that that particular hero has so based on the hero if that hero so if the case is superman i would say well that hero has console.log super strength may also have x-ray vision [Music] alright let’s add another case here and say case batman and notice that kind of the the format of this to use the case keyword inside of this block that belongs to the switch the case keyword the value we want to compare our our case against and then a semicolon and everything underneath that will become part of the body of that of that case that gets executed so in this case we’ll say what are batman superpowers he has intelligence and he has fighting skills all right and then we can also then say well the default for that hero is that they’re a member of the jla now watch how this works it works a little bit different than the if and else if so let’s go ahead and say what we have and then rerun this all right so in this case it was superman and notice that we matched the case superman because it prints out super strength and x-ray vision but then everything else inside of all additional cases including the default case will be true as well so he also is intelligent he has fighting skills and he’s a member of the jla now if we were to change this to let’s say batman and we were to run the application you’ll notice that it skips over all of the console log statements that describe superman superpowers and they they come in however here at batman so console log intelligence fighting skills and he’s also a member of jla now we could try somebody like a green arrow not particularly one of my favorite heroes and um he’s just a member of the jla all right now if we don’t want that that flow through style what we can do is actually use a break statement in here so let’s go back through this now and see what happens whenever we break out of a given case so back to superman and now when we run it we only see that he has super strength and x-ray vision batman has intelligent fighting skills and then um green arrow is just a member of the jla okay all right one other quick tip here is that whenever you’re evaluating strings there’s a possibility like for example batman what if we had capital b in batman all right and then we run the application and you see he’s a member of the jla why didn’t it catch the case batman because capital b batman is not the same as lowercase b batman in that string now what we can do to circumvent that whenever we’re working with strings and we want to do some comparison with them we can use the two lowercase method of our strings so strings have a built-in method called two lowercase and that will take whatever that input is and we’ll make sure that all the letters are lowercase so that we’re really comparing apples to apples instead of apples to oranges so now when we rerun the application we get what we would expect with batman okay all right so let me comment this out we’ve looked at the if statement we’ve looked at the switch and then the third one we’re going to look at is the ternary operator and this is useful whenever i want to i want to just do a quick inline evaluation of some expression and then return back a value a string number boolean whatever probably just a string or a number back depending on whether that expression evaluates a true or false very small short concise inline statement so i’m going to create two variables i’m going to do something a little bit different though the first variable i’ll create like you would normally expect but instead of ending that line and moving to the next one i’m going to do another variable creation variable declaration and assignment right here in the same line so i’m going to create another variable called b and initialize its value to the string one all right so just a slightly different technique you might see that online moving on so we’re going to create another variable called result and we’ll set that equal to some evaluation of an expression does a equal b so two uh equal signs that are next to each other is the equality operator this is a check for equality to say does a equal b and if that is true then what we’ll do is return the word equal as a string but if it’s not true notice the colon that separates the true from the false will return the word n equal so the ternary operator has kind of got several parts here there’s an expression there’s a question mark that that has true or false ramifications and we’ll just do a console.log result like so so now let’s go ahead and run that and these are equal great um we could also do this in line so let me just take this part right and do that instead you can see how we can basically perform that same check without having to create a new variable to hold the result all right so it’s a nice inline way of running a quick check and then returning back a string one string or another string now let me just go back for a second here or actually let’s do this and then we’ll do console.log result okay let me comment this one out i want to keep it around for you in case you want to reference that in the future um we used two equal signs but there’s another another type of equality that we can check for and that’s strict equality and this will check to make sure that these two values are equal but then in addition to that it will not coerce for example the number one and the string one it’ll say are these absolutely equal even with the same data types all right and so in this particular case we should expect a different result these are n equal they are not the same all right so these are the same because i’m looking for equality but if i’m looking at strict equality and i’m not allowing javascript to coerce the integer into a string and then check for equality uh then i have to say no these are not the same because one is a number one is a string all right all right so let me comment that out and let’s take do one more check here um in this case i’m going to use a different operator the not equal to operator so i’ll use the word not in equal and not not equal and not n equal all right which would be the same as saying equal alright so now let’s see and run that and this produces a false so this would be returned back and then displayed on screen but then we can also do strict inequality by adding another equal sign to that operator and these are not equal again because it is true that a is not strictly equal to b because they’re different data types all right hopefully that makes sense all right so let’s go ahead and stop there um and hopefully all this ternary operator business and and equality and strict equality makes sense and let’s move on you’re doing great we’ll see in the next video thanks in this video we’ll talk about iteration statements iterations allow us to loop through a body of code a block of code a number of times until a certain condition is met and there’s a couple of different types of iteration statements we’ll look at two in this lesson and we’ll even look at them in relationship to arrays something i promised several lessons ago so let’s start off by creating a new file and call it iterations.js and inside of here we’ll create our first for loop so four and then there are three parts inside of the opening and closing parentheses first of all [Music] we’ll let i equals zero or we can actually just shorthand this and not even use the keyword let here i less than 10 i plus plus and so this is going to take some explanation but let’s just get this working first and then i’ll come back and i’ll talk about it and we’ll just print out the value of i all right what do you think is going to happen here if i didn’t tell you anything about how the for loop actually works what do you think will be printed to screen when we execute our script let’s find out so let’s go here and type in node iterations all right so we get ano uh several it looks like 10 different values printed to screen each on a separate line zero through nine and then our application exits all right so let’s talk about this it’s a shorthand syntax and there’s three parts as separated by these two semicolons inside of this this evaluation header for the four first of all we declare variable in this case i’ve declared i that’s why we use the let but then i said well we don’t really don’t need it let’s keep it short so we’re declaring it and then we’re going to um initialize its value to zero the second step we’re going to say continue running this for loop as long as this condition is true so as long as i is less than 10 continue running the the body of this for loop as defined with this a set of curly braces here and then finally after you’ve run an iteration increment the value of i by one all right and here we’re going to then print out the value and that’s why we start at the value of 0 and then we work our way all the way through this 10 times on the 10th time i gets incremented to 10 this this check is performed it’s false and then we exit out of the program all right now let’s do something a little bit more interesting like i suggested before let me comment this out here let’s go let a equal two and this should look familiar 4 8 15 16 23 and 42 whoops i guess i forgot equal sign there and now what we’ll do is four i equals zero i is less than a dot length i plus plus inside the body of this we’ll do console.log a and what element will we use i because i will start off with the value of 0 and it will continue until we get to the length property which is not 0 based and once we get to for example the 0 1 2 3 4 5 so length will be 6 elements so once i is 6 it’s no longer true that i is less than the length of this array and will exit out so let’s go ahead and save this and then run and we can see we get all of our values printed out to screen so that’s the proper way to iterate through or one way i should say to iterate through an array now one thing about visual studio code that i really love is that they have this notion of code snippets so if you ever forget this this syntax and it can be a little daunting at first there’s a way to remember it perfectly every time and that is to let the code snippets build it for you so i type in the four keyword intellisense pops up with a little window under it and i’ll use the arrow keys to go to the for loop javascript all right there’s a couple of fours but the one that we want has this little box with dots underneath of it that tells me that this is a code snippet i hit enter on my keyboard and now i get the basic structure of my um of my for loop already created for the purpose of an array now notice that every word index is highlighted and i can change that every instance of that by just using a letter like i’m going to change this to the letter b instead of index and notice that it changed it everywhere and then i’m going to hit the enter key on my keyboard which is the wrong move then i’m going to hit the tab key on my keyboard and i can change the name of the array now everywhere the word array is used i can swap that out with the letter a for example i’ll use the tab key one more time here it puts me to the another replaceable area for the element and here i’ll use c i’ll use tab one more time and then it kind of exits me out of that snippet replacement structure and now i can continue on and type like console.log we’ll just print out c okay so let’s grab a from our previous example and then we get the same results we got before but this time we didn’t have to memorize exactly how to use for the code snippet walked us through and allowed us to replace the names of the various replaceable areas like the name of the counter the name of the array and the name of the given element c that we extract out of uh out of our of our array okay let’s comment that out that’s four and now let’s take a look at the while loop um so we’ll talk about the difference between these it may not be obvious at first but essentially we’ll do this all right so take a look at this knowing what you know about loops what do you think is going to happen here well we start off with 1 and we’re going to continue to execute this loop until this condition is false so the very first time we run it one is indeed less than 10 so we’ll continue to run the body the block that’s associated with our while statement and we’ll print out the value of x and then increment its value by one we’ll continue to do this until we increment the value of x and it becomes 10 at which point this is no longer true it becomes false and then we’ll break out and continue on so let’s go ahead and see what value what what the values that we get so we get one through nine that’s expected and once we hit 10 we break out great all right so what’s the difference between the while statement and this first for loop that we did here at the very top well the difference is that the for loop first of all has a lot of infrastructure that we have to build these three pieces and um it uses a series of indexes that represent the number of iterations that will move through this block of code now the while statement is a little bit different anything can be used to derive the iterations as long as this statement continues to be true we’ll continue to execute this block of code and so we control the number of iterations in the body in this case here i do the x plus plus now we don’t have to use counters we could use anything any kind of business logic like we may want to read to the end of a file and once we hit the end of the file it no longer it makes sense to continue to read each line of the file then we would want to break out so the while is a little bit more flexible and so much that we can build the business logic for how many times we’re going to iterate in the body of the uh the while statement whereas with the four we’re pretty much limited to the number of times we want to run this being the number of times that we’ve kind of pre-set it up here in this top section outside the body itself okay now there’s also one last thing we can talk about and that’s a way in both the for and the while we can kind of circumvent this check right here and we may want to do a check like this so if x is equal to 7 then we’ll call the break statement all right so learning what we’ve learned about the if statement it probably should look more like that right so let’s first of all let’s make sure it works all right in this case we’ve got one two three four five six once we reach the seven we circumvent this check and just say hey i want to break out of this all right so we can use that always to break out just like we broke out of the switch uh when we wanted to not let it flow through additional cases now the one thing i will say if you notice how i typed this to begin with let’s retype that so hold on let me comment this out so that you can see it in the code if you want to download my code but we could also do it a little bit more shorter and in line since i only have one statement that i want to make right after the if statement i can do it on the same line and i don’t need to surround it with a code block a code block indicates that there’s usually more than one line of code in this case there’s just one line of code i could put it on the separate line and use some indentation like that or i can just keep it all on the same line since it’s so short but that might improve readability or i might decide that this is a more readable form that’s kind of up to me and if i’m working on it with a team of software developers i might want to get and kind of do it the way that they do it but stylistic for me this is so short i can read it all in one shot if x is seven then break out of it it just it looks good it’s very readable i’ll be able to understand what i’m doing later on it doesn’t take up and move the code down so i like that that format if i just need to create one statement right after my if right after my if so sometimes it makes sense to split things on separate lines sometimes it makes sense to keep two different statements on the same line again i think it kind of is a stylistic choice that you’ll have to make for yourself at some point all right so that is iteration statements we looked at two different kinds and we looked at how code snippets can be used to help us remember the format now i believe the while has in fact i believe most of the things that we’ve looked at has um uh some uh some code snippets available to them like if i find it here in intellisense you hit enter on the keyboard but there’s not as much to it there i mean while with the condition i can change this to x is less than 10 right it’s not so much for me to type that out but the four makes a little bit more sense because there’s so many parts to it and replaceable parts of that okay so let’s continue on the next video we’ll see there thanks it seems like quite a while ago we talked about variables but now that we’re working with blocks of code inside of blocks of code like we had here in lines number 23 and then 29 through 31 we need to talk about variable scope and when i use the term scope i mean variables are a little bit like people in so much that variables have a lifespan they’re born they do work and then they die and they’re removed from computers memory when they go out of scope and we’ll see an example of of that in just a moment but they’re also like people in so much that they have a citizenship i guess you can say in other words depending on where they were born they can work inside of some code blocks but not other code blocks and so the remainder of this video we’re going to look at lifetime and availability or citizenship i guess you can say inside of the rest of your application so let me create a new file and we’re going to call this scope basics and there will be more to say about scope as we move forward and learn more about functions and so on in just a little while here but let’s start and create first example here so let a equals first i’m going to create a function called scope test and inside here i’ll just do a console.log and the first thing i want to see is if i declare variable out here outside of my function can i reference it inside of my function and so to find out let’s just call scope test and see what we get so here we’re going to type node scope basics and we can in fact view the value of a variable that was declared outside of the scope of a function we can view it inside of the scope of that function all right so the next thing that i want to do is to say hey let’s create a variable here now if i create a variable inside of a function scope can i view it out here outside of the function scope so console.log b and let’s see and so no not only can i not see it but my application actually blows up and you can see the little carrot here is right underneath the b and it says b is not defined so in other words you could kind of think of it again in terms of the life span we created a function and we created a variable inside of that function that variable lives as long as that function is running but after the function after that code block is has completed executing then b is removed from the computer’s memory and essentially thrown away therefore we cannot reference that variable outside of the function because it no longer lives it’s dead all right so we’re gonna have to comment that out and we can go ahead and comment this out as well now let’s do one more thing here let’s say if a and we’ll just do something silly here if it’s not equal to an empty string so just two single quote marks next to each other so uh then can we still see the value of a even inside this innermost block of code that we defined with an if statement if we can we should see then it printed here a second time the value first so let’s save what we have let’s run this again and so we see first first the first time it’s printed out and the second time that is printed out all right so yes if something is declared in an outside scope it is visible or it can it has citizenship in every inner scope from that point on but here once again if we were to create a variable third and then try to reference it outside of the code block in which it was defined like so will this work what do you think we’re going to get that same kind of error before we get the little arrow pointing to the c and it says that c is not defined the variable c was defined inside of this code block and once we executed that code block and got to the end of it then it c was removed from the computer’s memory it’s no longer available to us in a sense dies and it’s no longer available okay now let’s just do one last thing here just to to kind of understand that we are in fact able to work with uh the variable that was defined in the outermost scope can we still work with it do it use it and change its value so i’m going to change this to changed and then i’m going to reference it here console.log a and so now let’s run our application one more time all right so the first time that it’s run this first console.log it will be the value first but then we change the value and we log it again and that’s where the second change comes from after we’ve executed that function then we execute line 20 and that’s where this third changed appears all right so i guess the moral of the story once again to kind of reiterate what we said when you declare a variable you have to understand in which scope it was defined because based on the scope or rather the code block in which that variable is defined it’s going to have a life span and it’s going to have citizenship if it was defined in the outermost scope it will have its life and its citizenship in all inner scopes but if it’s defined in an innermost scope it will not be available to outer scopes now one last thing and i’ll kind of end it right here if we were to take and this is probably just a question for you just a thought question if i define b here right above that if statement and then i attempt to use it right here and call this inside if do you think that will be able to reference that value well based on what we know about the rules i would expect to see the value second printed out so let’s try it and in fact we do see it so hopefully that supports your new understanding of the scope of variables defining them outside of a code block versus defining them inside of a code block and trying to reference them outside okay so hopefully that all makes sense want to make sure you’re clear on that we’re going to revisit the topic of scope because there’s a lot more to this but this is your first introduction so that you kind of understand what the rules of scope are at least in the most basic sense all right so we’ll continue on the next video see you there thanks scope is a topic that will keep coming back to over and over throughout this course it’s important because at least when your javascript is run inside of a web browser you must be aware of the topmost level of scope which is referred to as global scope in node like we’re using here it’s not as much of an issue they’ve got some safeguards against it but in web development working against the global scope is a crucial concern a lot of consternation and consequently a lot of effort has been exerted to preach that declaring variables at the global scope is a bad idea so you would never want to do something let me create a new file here returning functions.js js there we go you never want to do something like this note the use of the var keyword and you never want to do something like this although you’re more likely to do it than the previous line in line number one now the reasons why you would never want to do that this will require a little bit more explanation a little bit down the road and i’ll make this point emphatically when we start writing javascript for the web browser later on in this course but for now just understand that much of what i’ll say and why i say it over the course of the next five or six lessons or so will be working towards a solution to avoid writing your code in the global scope if at all possible now the eventual solution that i want to demonstrate relies on how javascript functions work but we need to take a few baby steps to get there so the first aspect of this technique that i want to demonstrate has to do with returning a function from a function now up until now our functions performed one or more actions and then exited quietly we may have returned a simple value like true or high or something along those lines however we can create functions that can not only perform some action but then at the very end can return a value to the caller and not just any value can return a function so let me comment all this stuff out and i’ll say don’t do this to make sure you never do that and this either and then i’ll just uh do a multi-line comment here and so let’s start off really simple this is something that we’ve already talked about when we talked about declaring functions or function declarations so here’s function one and inside of function one we can just return the string one right it’s not very exciting but it demonstrates the point that you can use the return keyword to return a value to which ever calls that so for example let value equals one for example and what would we expect to be in our variable value well we would expect to print out the string o n e or one so console dot log and value like so and just to see this working let’s go ahead say node and then returning functions and we see it returns here at the bottom of our screen the string one as we’d hoped now we could also kind of paraphrase this make this a little simpler by just doing it all in one line right so we could put the call to the function and not use a variable we could just make the call to the function which returns a string and that returned value will automatically be passed into the console.log method let’s save that hopefully that makes sense and that’s a common technique that we’ll want to use but things start to get a little bit more mind-bending when you start to think of a function as just another data type in javascript so for example um let’s go back to this i’m gonna copy this again and then let’s go um console.log and then type of [Music] value all right and [Music] well let’s do this let’s get rid of the method invocation operator so now we’re just setting a reference called value to our function one let’s see what we get and you can see the type is function so let’s think about all the data types we know about now we know about string we know about number we know about boolean we know about undefined and we know about function right and we’re going to learn a couple more before this is all said and done but at any rate notice here again i’m just in fact we could even do this a little bit differently i may have muddied the waters by introducing a variable let’s just do that instead and we should get the same the same result all right so uh i guess the heart of the matter here is that we can get a reference to a function and we can store that reference to the function out in uh in a variable which means we could also do something like this so now we have a reference to the function we can call the function using the method invocation or the function invocation operator so let’s go ahead and run it whoops i guess we need to actually then go console.log there we go now we’re getting somewhere there we go okay so hopefully that makes sense i just have a variable pointing to the function and then now that i have a variable point of the function i can execute the function by just using that variable with our method and location operator right all right hopefully you’re still with me so far hopefully this isn’t too mind bending let’s continue on here so since a function is just a data type like any other data type that we’ve learned about so far our functions could return a function because we’re just returning a value right and that value can be any type so in other words let’s let’s do this function two and here we’re going to return a function now this is a function expression inside of a function declaration right and here console.log and 2 like so and then do something like let my function equal 2 now what gets returned to my function it will be this inner function expression so i should be able to do something like my function with the method invocation operators and let’s see what we get and we get the value 2 like we’d hoped all right so hopefully you can see here we’re using the return keyword to return a function expression we get a reference to that function expression by calling the outer function declaration now we have a function in hand or reference to that function this inner function right here and we merely invoke it hopefully all that makes sense and we might be able to do this a little bit differently let’s try just a slightly different tact so here i’m going to go function three and here i’m going to return um function and then return three all right oops let me spell return correctly all right so in this case i’m returning a function that returns a string so i should be able to do something like console.log and then i’m going to call 3 what do i get back from that i should get back a function so i should be able to invoke that function to get back the string to give to the console.log now you would never do this and you would never see this but this is just to illustrate a point that um of what you’re really working with and that’s references whoops let’s actually execute it there we go three what you’re you’re working with here are references to functions that can return references to other things and maybe even other functions right so again that last one’s pretty far-fetched you probably never do that but the fact is that what gets returned from our three function declaration is a function and then it can be invoked with the function invocation operator here the second set of inner parentheses right there all right so on the surface this might not seem like a very significant development in our javascript journey but nothing actually could be further from the truth because this is actually a huge step towards moving our code out of the global namespace like i talked about the beginning of this video but to complete the story again we have several more baby steps to go we’re going to need to step away from functions for a little bit and come back to them once we’ve learned a little bit more about arrays and objects and objects specifically all right so just keep this thought in mind and we’ll continue on you’re doing great hang in there we’ll see in the next video thanks if you remember uh when we were looking at arrays i did the type of on an array and it returned back the word object so that’s actually another data type in javascript that we haven’t looked at until now obviously given the title of this lesson we’re going to look at objects so an object is similar to an array in some ways but its intent is dramatically different an array will hold a list of information in other words there may be many data items whether they’re strings or numbers or booleans or even objects each stored in a different element of the array contrast that to how an object works an object contains the related properties of a single data element so array many data elements an object one data element but has attributes so the settings of the properties define the characteristics of the object so let’s say for example that you want to have a car and so an array will only really let you save maybe the year of the car or the make of the car or the model of the car as a string or maybe some identifying number but an object would allow us to define all of those properties kind of in the same container so you know if you try to keep track of all the properties and maybe even all the methods that that belong to a car but you keep them as separate variables and separate functions you’d run the risk of clashing with other variables and functions that have the same name for a different car okay but objects let us keep that information kind of safely locked away in their own little container where the relationship between all those properties and functions uh are obvious that they all kind of belong together to describe one car and then you might have another object that describes a different car and you can keep both of those objects those two cars in an array of cars so hopefully you can see the relationship between those all right so um let me first of all start out by creating and you file object.js and so um you know i may have an object that has a series of properties that describe a specific car and i might want to for example keep track of the make the model in the year and so on and i may have some functions that i need as well things like uh getting the price of the car based on some criteria maybe you know the year of the car and things of that nature and i may want to print out a special description of the car that includes many things like the make the model of the year in a special format but i might define a car object like so so let’s do um let car equals and then we define an object using a um a code block so curly braces now i’m going to use kind of a name value pair here so let me just go ahead and start typing all right take a second and catch up with me there if you like now let’s go ahead and use the print description function like so and let’s use the year property like so i’m going to save my work and then i’m going to type in node object or object and the first printout is bmw 745li because we’re printing out the make and the model of this car all right and then here i’m just getting the year of the car and printing that out in a console window all right so in this case this object that i’ve built on screen we’re dealing with a tangible real world and very relatable concept that of a car we’ve all driven in cars or have driven cars in your javascript code you’ll occasionally be working with objects that define tangible real world things like cars but you’re also going to work with things that represent more abstract concepts that are specific to web client or web server development so in this sample i created an object using what’s called object literal syntax so i literally want to create this object and then i’m going to assign that object to a variable named car and the body of the object is like i pointed out defined with cur a series of curly braces here this set of curly braces at the outermost level here this defines kind of the boundaries for the object and everything that lives inside of it is either a property of that object or a function called a method inside of that inside of that object so let’s start off in lines three four and five here we have a list of name value pairs so here’s the name of the property and here’s the value of the property in this case notice that each of the names of the properties are just identifiers they’re just like variables in fact you’ll probably want to use the same naming conventions that you would use inside of with a variable and then the values can be any data type in this case i have a literal string bmw a literal string 745li and a literal number 2010 that represents the year all right and notice that the property and the value are separated by the colon character all right and then each property definition as well as each function up until the last one are separated by commas now i put each of these properties and functions on their own line or series of lines as it might be for the functions in order so that we could see some readability but that’s not entirely necessary from javascript’s perspective it would be fine if we put all this on one line of code all right so again with regards to the names of both properties and these functions which i call methods you’ll want to use the same naming conventions that we used previously when we talked about variables now there’s some other ways to create objects and i’ll discuss another technique in one of the upcoming lessons um so uh we’ll come back to that notion because it’ll lead into another discussion that kind of takes us off at a whole other tangent that i don’t want to go on right now so um here we define the function kind of the same notion i gave it an identifier the name of the function that i want to access and then i’m using a function expression and define the function expression within uh several lines here but essentially we’re just returning a value or in the case of the second one just just calling console.log we could write any uh number of lines of code inside of here these are just happen to be very simple for the purpose of illustration all right so i’ve defined my object now i want to actually use it and reference it how do i do that well you can see that whenever i wanted to access a specific property of my object or when i wanted to access a function i use the variable name that i set the object reference to and then i use the period on the keyboard that which i call the um the property access operator just the dot on the keyboard same is true when access of accessing a function as you can see here in line number 15 i used that period that member access operator and then you know all else is fair this is a function so i’m going to use the method invocation operator just like i would to invoke a normal function now uh i i keep referring to these functions that are inside of a an object as a method and and i think you should probably start referring to functions defined inside of objects as methods it’s a more descriptive term and i’m already used to it for my work with other programming languages but simply put a method as a function that belongs to or rather is defined inside of an object now there’s another syntax that i could use in addition to what you see here and it opens up some interesting possibilities that frankly i’m not very fond of but you could definitely do something like this so it almost looks like i’m using the array uh array element accessor to access a specific property here let me go ahead and save that so we’ll see the year appear twice here if all goes well and we do at the bottom so that’s one approach to accessing an individual property and the other is similar uh but it uses a um an index so it’s actually kind of interesting how this works um what is the the fur or index one of my car let’s find out the hard way here and it’s set to undefined in this case so actually it doesn’t reference any of these it basically creates its own new property and sets its value to undefined let’s never do that let’s not do that i prefer the dot syntax again it’s going to be most familiar to those of us coming from other programming languages but you could in some advanced scenarios use these techniques to do something a little more advanced and that’s way beyond the scope of this of this lesson all right so i recommend you just use that dot notation for now and all will be happy so um you can do like i kind of mentioned a second ago some pretty advanced things with objects and there’s a lot of room for variation so i’d recommend taking a look and taking notice of how other people work with objects in their javascript code as you’re perusing the internet because there’s always seems to be a new twist i think i understand how objects work and then i’ll see somebody do something really extreme and interesting and i’m like wow that that opens up my understanding a little bit more to how objects work i’ll just give you a quick example of what i’m talking about here here we can create a another car and i can create an empty object like so and then i don’t have any properties inside of my another car how do i reference another properties of inside of that well what i can do is just um kind of just say hey i want to create a property here called whatever and i’ll set it equal to bob all right and it’ll just automatically create a property called whatever and set its value equal to bob just like that no let or var keyword or anything if i do console.log um you’ll see that card.whatever in fact will come out to be bob or i thought it would oh i think what i’m going to need to do is save my work here and then do try this again whoops oh i’m sorry another car i had the wrong reference it didn’t exist on car but we need to look at another car dot whatever and there we go there’s bob okay so just an interesting feature of objects you can you can add properties kind of ad hoc and some people do that and that is kind of a feature not really a bug of javascript it’s dynamically typed you can just say hey i need a property here i need a function here and you attach it to an existing object and there it is it’s you’ve got an object now with this additional property called whatever all right um you can also do some other kind of interesting things might as well take a few moments and look at these so um i’m feeling unoriginal now so i’m going to create a new object called a and inside of this i’m going to create uh my property and i’m going to actually set that to another object i’ll define a property inside of that and i’ll just say hi because again i’m feeling rather unoriginal um and so let’s figure out how can we actually print out the a uh so console.log a dot my property dot b will i get what i think i’ll get i will so you can see how i can chain things together whether they be functions or properties by just continuing to use you know this is an object that has a property that has an object that has a property and so i can kind of chain through and and create essentially what becomes a namespace and we’ll reference that a little bit later when we talk about solving the global name space issue or or putting our variables at the at the global level of our of our applications which we’re trying to avoid all right let’s take a look at another quick cool example of things you can do with objects that might not be so obvious at first glance so here i’ll create var c and inside of that i’m going to create another my property and this time i want to create an array so this property the value of my property now will be an array of i could do strings i could do numbers but i could do an array of objects so all right and that’s perfectly valid so here think with me again i have an object that has a property that contains an array of objects that each have different properties all right and that’s perfectly valid so objects can contain properties of the type array that can contain other objects that can contain well really just whatever makes sense for your application however you need to store it and kind of represent the data that you’re working with also if you’re going to work with an array of objects it might make sense for all of them to have the same set of properties like in this case each object has a different property i’m not so sure that would be so useful but it might be something that you need to model in your application there’s nothing forcing you to keep the same set of properties for any given object uh inside of an array of that of that object you know as long as your javascript code or whatever will consume this object understands how to interpret it that’s all that matters so once you get past the simple hierarchy of values you typically refer to something like this that gets a little more complicated as an object graph a graph of objects all right just keep that in mind let me paste in some more interesting examples here just kind of get expand your thought process on how to work with objects let’s say i have a car lot and i want to store an array of objects each object has year make and model all right then i could iterate through the car lot and print the screen each of those individual car objects right so that’s one example how about um you know if this was more of a of a yes you could say a system that kept track of all of our customers and employees we might do something like this this gets a little more complicated and unfortunately runs off the side of the screen a little bit but you can see here i’m creating a contacts object here’s the start in the end and inside of that i have a property called customers and a property called employees now both of these have as you can see an array of objects and these objects look very similar and so much that they have a first name last name and then phone numbers and then phone numbers actually is an array of strings in this case this particular what is he a customer this customer bob tabor has two phone numbers richard bowden has two phone numbers and then but our employees like steve and conrad and grant well steve has two phone numbers but connor and grant only have one full number all right so you can see that things can get pretty crazy really quick but that’s a perfectly valid object initializer it just happens to be a little bit more complex than the ones that we started off with so now as you’re looking at this you might think to yourself wow this this actually looks similar where have i seen this before it looks a lot like jason have you heard of jason json or js json i guess some people put the emphasis on the on it’s short for javascript object notation json is both descriptive and compact and it’s probably the most popular way to send information between two disparate systems so we might in fact use it uh to store um settings or properties inside of um you know a more advanced javascript application or they use it in visual studio and c sharp projects to store application settings for example now in in the new version of c sharp and net um we might use it in our application sooner than later to send data between a single page application that lives on the client and the backing web api that on a web server that hosts a web api if none of that made sense don’t worry about it eventually you’ll get to that point if you continue on learning javascript all right so what was my point here well if you’re familiar with what json is you might notice that there are a lot of similarities between the object literals that we’ve looked at in this video and jason however there are some subtle but important differences between the two and i’m not going to take the time to go through that you can easily do a quick search online to see what the differences are between object literals and javascript and the javascript object notation or json just be aware that these are not one in the same there are subtle differences you cannot use them interchangeably but their syntax is very very similar and json or i’m sorry javascript has a built-in function that i’ll let you work with jason as you might expect okay wow i’ve really gone along on this one but objects are pretty important and we’re going to use them a lot and there’s a lot to them in fact we’re probably going to be talking about them a couple more times before the end of this course maybe even in the very next video so you’re doing great hang in there we’ll see in the next video thanks previously i said that much effort and education is centered around the dangers of defining variables and functions in in the global scope also referred to as the global name space especially when writing javascript that will ultimately be targeted at running in a web browser but i never really answered the question why is it dangerous i never kind of ventured into that and i’m going to illustrate more clearly later on why this is dangerous and how you can really hurt yourself when you are creating variables and functions in the global scope but in a nutshell the global scope is global so number one each variable that you define to the global scope is not removed from the computer’s memory until the web browser or the tab of the web browser navigates to a new web page so the more that you add into that global scope the more memory you’re taking up and that memory just is is consumed the entire time that that tab is open uh for that particular web page but more importantly number two um again emphasizing that this is the case with javascript in the web browser not so much true whenever you’re building these node style applications as you load javascript that you wrote and you rely on javascript code that others write whether that be code that javascript libraries that you’ve downloaded from the internet or that you include your project somehow maybe they’re ones that other people in your company have written and you need to include them in your project or perhaps even sold commercially online some product that you purchased came with a javascript file and you included maybe it hasn’t been updated in a number of years the variables and the functions that are defined in those files when you consider the the the variables and the functions that you’ve written in your files there’s a the more that you write at the global scope the more that they wrote at the global scope if they didn’t take precaution the more likely you’re gonna have a collision of names at some point somewhere down the road somebody’s gonna have a variable named what you named and they’re both trying to contend for uh the global for being the variable the winner in the global scope so we call these naming collisions uh and when these naming collisions happen either your data will get overwritten by their code or their data will be overwritten by your code but either way undoubtedly it’ll cause unanticipated uh bugs that are difficult to track down and quite frustrating and the reason why this is even a thing is because it’s happened okay so now that it’s happened everybody is extremely concerned about it and so a series of suggestions came out and and a lot of effort went again around trying to figure out how to solve this issue given the the tools in javascript that they had available and the first one that has come out and that i’ve recommended from the very first lines of code that we’ve written is to use the let keyword start the instead of the var keyword because the var keyword will attach variables to the global scope which in a web browser is the window object in the document object model we’ll talk about that a little bit later and i it’s also recommended that you use the technique the design pattern that we’re going to discuss in this video whenever you’re writing javascript code or there’s a third option too which is new in javascript in the latest version of javascript called modules unfortunately and i may even talk about this at more length later on the implementation of modules is a little bit uneven between node and the web browsing environment so i’m not sure how helpful that would be at least as we’re getting started and learning about javascript just keep in mind there’s several different attacks but this is probably the one that you’ll see used most often in at least uh javascript that’s been written over the course of the last five to ten years but there are some newer ways to to tackle this all right so any rate the technique that i’m going to discuss in this video or the design pattern actually uses a couple of techniques that we’ve learned about so far we’re going to use an iffy remember what that is an immediately invoked function expression to create a function and then that function will return an object and that object will have defined functions and variables that will then be kind of scoped to one variable so instead of having five or ten variables that we’ll have only one variable in the global scope uh or at least in some scope and then we’ll be able to reference the individual uh variables and property variables and functions of that particular object that gets returned all right so we’ll see how variables and functions can be made essentially private so that we can hide some implementations from the ability for just any code to call them this is often called encapsulation in software development terms and so these will be unavailable outside of the public variables and the public functions that we return and that’s generally a good thing so there will be a couple of benefits that come out of this all right so um let’s get started by creating a new uh a new file called module pattern dot js all right so let’s start by creating an iffy and to do that hopefully you remember how to do that we’re going to start with a function expression we’ll just create an empty one to start off with we wrap it in a set of parentheses and then we use another set of parentheses to actually invoke it all right so what i’m going to do before we get any further is actually set this immediately invoked function expression to a variable i’m going to call this counter so i’ll set counter equal to whatever is returned so eventually what we’re going to do here is return an object full of properties properties that have values properties that point to functions that can be called but we can also do some private stuff here and this will not be accessible outside of the calling the counter dot something to access it and so we can like have a private variable here like let count equals zero and we would not be able to do counter.count it just wouldn’t be accessible we’ll fix that here in a moment when we return an object will give an accessor to it we’ll take a couple of passes at that actually okay so um let’s go and create now a private function as well and this will just print out a message and style it up a little bit differently so we won’t get crazy here so console.log and um we’ll just uh say whatever the message is and then we’ll just do like three dashes like that just a little bit of style just to show that you know we have something here that could be private but now ultimately what we want to do is return an object that will get set to counter here all right so um [Music] we’re going to start off simple we’ll come back to this a little bit later because there’s going to be a issue with one part of this actually this part right here what if i just want to return back the counter the current value or rather the current value of count i can try that again we’ll come back to that in a minute but let’s say we create like an increment increment property and it will return a function and inside that function we can do something like count plus equal to one and uh then we can call the our print method and then just say after increment something like that we can also here let me use a comma right there because we’re going to create another property of our return object called uh reset and what this we’ll do is call a function so we’ll create another function expression print before reset then we’ll call the count and then print or we’ll set count equal to zero because that’s the point of a reset and then after reset it should always display zero but let’s just double check that all right so now we have basically our uh our module pattern we created a module which is essentially an iffy that returns an object that will expose functions and other properties like um like the current count and now here because i’ve invoked this immediately this is available it’s already been executed and counter now is fully populated and ready to be used in our application so i can do counter dot value i think wasn’t that the name of it i’ve forgotten everything already okay i value so console.log counter.value and um i could try to do console.logcounter.count [Music] just to prove that it won’t give me anything back so let’s just start there and we’ll go node module pattern and first time we get an undefined wide because count is not a property of counter uh because we didn’t it’s it’s not exposed and it’s not being returned in the return object all right so that is impossible now what we can do however or we will try to do is call counter oops counter dot increment you can see it shows up in intellisense that’s a good sign so we’ll call increment in fact let’s call it like three times whoops kind of ended up below where i wanted to go there all right great and then we’ll call counter dot reset like so all right so let’s see we get this time it’s not gonna quite be as satisfying uh because we’re gonna get a little issue on on uh on these lines here so you can see after the increment the value is one two and three but then when we attempt to get the value of counter from this property count it we would assume it would be three right but it’s zero what happened here well we accidentally created something called a closure and another little topic we need to talk about in javascript so let’s not do that we’re going to need a different way to implement this basic functionality so can’t use this technique what we’re going to need to do is take a different tact and we’re going to implement two more functions here we’ll create a set function or i’m sorry let’s start with a get function and get we’ll do something super simple it’s just going to return count and then and i did it all in one line put it down on multiple lines didn’t need to it’s pretty simple function and here we’re going to set count equal to some value that’s going to be passed in so here we’ll say we’ll accept an input parameter called value making sure we add some commas in between these new properties here that are set to these functions we’ll take in some value and we’ll set count equal to that so we should be able to come down here and now since we’ve kind of removed that let’s go counter dot get or actually let’s set it to the value of seven here we’ll do a console.log counter dot get to ensure that it is seven and then we’ll call our reset let’s see what we get when we run it this time all right this is a little bit more interesting well almost interesting i need to invoke get okay so i forgot that save it run it one more time [Music] there we go okay so here we go lines 33 through 35 will produce these three lines where we’re after increment one two and three then we call counter set passing in the value seven and so we then do console.log get counter get and we get that seven back out now we call reset and before the reset the value will be seven after the reset we reset it to zero okay so hopefully you can see that this technique of returning an object from an iffy will first of all allow us to keep some implementation deals details private like we couldn’t get to count and we didn’t try but we wouldn’t be able to get to print because only certain things are being returned um and mostly in in terms of functions uh that give us access to the private functionality and a little bit more but in addition to that we’ve reduced think of all these variables that we’ve reduced out of the global out of global scope there’s no count variable now there’s no print there’s no get set increment or reset they’re all part of this one variable called counter and so there’s less of a chance that we’re our namespaces are going to collide as a result of that now we want to pick something unique there maybe something that describes a little bit better uh what the intent of this is maybe something specific to our brand or company and and maybe pick something fairly unique there but as a result of that we’ve protected ourselves and written our code a little bit more defensively now there’s one more thing that i want to talk about here and that is that uh okay so keep in mind this this technique that i’ve just demonstrated here is so popular that it has a name this is the module pattern there’s another variation that was created on this called the revealing module pattern you might see this used as well let’s go ahead and create another file and i’m going to call this reveal revealing module.js all right and i’m just going to paste some code in so that we can kind of compare and contrast the two versions all right so it’s it’s nearly very similar in so much that we have an iffy that we’ve defined inside of that iffy we have some private stuff just like we had before here we have some more private stuff these are the implementations of get set increment and reset but i’ve created these as uh function declarations with names now here at the bottom we have this is the revealing part of the revealing module pattern here i’m revealing publicly accessible uh functions by including them as properties in this return object so i can call counter dot get in counter dot set exactly the way that i could before but behind the scenes they’re calling the implementations that are defined here and so there’s a couple of benefits and a couple of downsides first of all it what makes it a revealing module pattern is that it reveals the public functions through these properties in the return object okay and it’s a clear a cleaner clear presentation of what actually gets returned but there is a downside and that is you can accidentally overwrite these are just properties so i could set the value to the get equals seven and not and forget the method invocation operator and as a result i can pretty much just break the association between get and the function name getcount and so that’s a downside we could accidentally break this whereas in our module pattern um you can’t really do it that’s not possible okay so um that’s the module pattern the revealing module pattern it brings together a bunch of techniques we’ve learned all to the greater good of removing or reducing rather our impact on the global namespace by removing variable names and function names from our from the global scope okay and we’ll see why that’s important on the web development side of things as we move in that direction but wanted to kind of bring all that to a head all right so let’s uh continue on in the next video we’ll see you there thanks as you’re getting started closures can be another mind-bending topic in javascript but they don’t have to be if you understand them you can really unlock the power of javascript now having said that personally i don’t rely on them very often when i write code but i’m not a javascript ninja so your mileage may vary you’re going to see a lot of articles and tutorials out there that talk about closures and i think sometimes they make things more difficult than they really need to so i hope to provide a really simple uh explanation that will simplify this topic for you and you can get into some of the more advanced stuff a little bit later on but basically a closure allows you to associate some data with a function and then use the function with that data already kind of baked into it from that point on in my mind it’s kind of like this i’m basically taking a function and i’m marrying it to some data through an input parameter an input argument and then they live happily ever after in their own variable and from that point on they work together as a team whenever i want to invoke that function with that data already pre-filled i guess you could say into the input parameters i can call that new variable all right that’s all it is um and then well okay there’s more to it than that but for the most part that’s all there is so let’s just create a really simple example or two and and hopefully it’ll clear some things up so uh let’s create a new file called closures dot js and let’s start with just a function i’m gonna create something super simple say hello and then inside of here i’m gonna return a function because that’s kind of the point of this and it’ll just say howdy and i guess we’re going to pass in a name so howdy plus the name all right all right so that’s really step one i create a function that returns a function looks like i got a little problem here whoops i return a function there we go uh so here’s the function returns a function and i’m passing in a argument called name that i’ll ultimately use in the body of this return function all right so then i can actually make a call so for example let bob equal say hello and passing in bob now from this point on um i call bob well we’ll see what happens here node closures all right howdy bob all right so um by itself it isn’t all that impressive but that’s really kind of step two and three all in one shot so i can pass in some variable that slightly modifies the way that this return function operates so in this case it’s pretty simple i’m passing in a name and it will change what gets printed out every time whenever you call this function in the console.log all right so this value is basically um saved off in a variable outside of the returned function so we’re lying relying on how scoping works in order to get that closure behavior that name kind of follows along this return function everywhere it goes bob gets passed along from that point on and then this is step three where i save that off in its own variable so that i can call from that point on and i kind of get this say hello with bob prefilled right so i can do the same thing with um conrad say hello and then grant say hello and that’s all a closure really is so let’s those and there you go three versions of the same function that get returned we modify the operation by taking advantage of how scoping works in javascript by kind of giving it this value that it’s going to hold in its own in its own context from that point on uh in stored in the these separate variables all right so this is really uh just the binding process uh that binds these together and then stores them off that’s all it really is so another way to look at this the say hello method has finished executing and it returns a function but in the environment in which the method originally ran it preserved that so that whatever value we passed in is preserved inside of this return function the environment or in this case just the name input parameter this variable name remains available so now in step four i guess you could say if there was a step four i basically use the new variable which represents a call to the method and a preset input parameter to conveniently call that version of my function now all right so um the important lesson to take away is that each closer closure creates its own what’s called lexical environment and you’ll see the term lexical used a lot in javascript uh whenever you’re learning about scope i’ve tried to steer away from that term because i feel like maybe it clouds the issue a little bit it’s basically just a fancy word for everything that we learned about in the scope basics here previously where if you define a variable outside of a function it is available inside the function but if you define it in a child code block essentially it’s not available outside of that child code block so that’s basically what i mean by lexical scope it basically defines how a parser resolves variable names and functions when they’re nested and the word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available from that point on throughout the rest of your code so nested functions like we have here in our sayhello that returns a function have access to the variables that are declared here outside of it as well as any of the input parameters that are declared outside of it and uh outside of their original scope right and that’s just how the lexical rules work like we learned about in scope basics.js so when we create a closure each closure gets its own lexical environment meaning that they get each time we create one like we do here in lines 8-10 they get their own set of variables their own name variable and anything else we were to define outside of the function in this case we don’t have anything else and there’s more to closures you can get in some pretty advanced scenarios they’re a powerful concept in javascript the ability to retain or bind to the lexical environment of the variables that enclose the returned function like in lines three through five to create a version of the function with some values already pre-applied is pretty powerful if you don’t completely understand that that’s okay don’t get discouraged for now just understand that whenever you return a function from a function you also glue any of the variables that were defined outside of the return function including in this case our input parameters all right that’s all you need to know about closures well for now anyway all right so let’s continue on in the next video you’re doing great see you there thanks if you think back to the lesson on object literals i think we were working in the object.js file i created a car object with several properties and functions and you can see that i’ve created a new file called this dash keyword dot js if you’re pausing the video to follow along then you might want to go ahead and create this dash keyword dot html yeah that’s right we’re going to write some javascript in an html page for the very first time in this course here in lesson number 18 because i want to show you how this works in different contexts this keyword but getting back to the point at hand if you recall that example that i’ve pasted in from that object.js file into this keyword.js uh you see line number 10 and at the time i didn’t even proffer an explanation as to what this dot make and this dot model actually mean in our in our application uh the fact is that this keyword can be a little bit challenging uh so even people with a little bit of javascript experience from time to time get a little confused about this keyword and one of the reasons people get confused about it is because it means something different in javascript than in most other programming languages so you actually have to kind of fight your existing knowledge so if you’re coming from another programming language the best thing you can do is kind of just leave everything you think you know about ja about well a lot of topics but in particular about the this keyword at the door and if you are just coming to javascript as your first programming language then you might even have a slight advantage here because you won’t have to fight yourself in what you think you know but simply put the this keyword in javascript represents the way a given function is called the way a function is called will determine what this represents okay so you essentially bind this keyword to a given context uh and we’ll explain what that means based on how you call the function all right so up to now we’ve not really paid much attention to how we call functions i told you there was really only one way to call a function using the method invocation operator so we would do something like this a little bit later on right like a car dot print description all right and i used the method invocation operator and i didn’t even hint to the possibility that there would be another way or multiple ways to actually invoke a function but that’s actually pretty important when you consider what this keyword represents all right you’re going to learn in this video at least that there are other ways to call a method that allow you to set or rather bind this keyword to something so that you can do something interesting inside of in this case your object or your function or whatever the case might be now you may never need to do this but it’s important to understand the basic rules and how that this keyword gets bound to a context and gets referenced inside of your object or your function there’s an entire book written about how this functionality works and all the permutations and and it’s awesome it’s a little bit over my head at times so i’m going to give you an absolute beginner’s explanation as to how this all works but it should serve you well as you’re getting started and then you can refine your understanding a little bit later on but let’s start off and by commenting out everything and you know what there’s a really easy way to comment out everything that i haven’t talked about yet alt shift and a on your keyboard will add a uh beginning and an ending uh code comment character operator to whatever you have selected so that’s a nice quick way to do that great all right so let’s start really simply i’m just going to create a function called first and this function is going to return the value of this what is the value of this well um here if you go console.log first is it equal to the global object inside of node so the global object we’ll talk about that a little bit later i guess it is kind of the the most basic context of things that get uh executed inside of so when we create something in the global namespace a global variable we would create it essentially attached to the global namespace it’s available everywhere in our application all right so let’s see if when we call first from line number 20 is this which gets returned equal to the global the global object so let’s go this dash keyword and it is true all right so when i call the first method basically from the global context because i haven’t created it inside of uh using the module pattern inside an iffy remember what we talked about previously so i’m i’m basically just calling this here out in the global namespace and what gets returned back is the fact that this is equal to that global namespace all right so now let’s try something else actually let me just do this let me copy this little comment that i have in my notes because it might be helpful to you for reference all right so let’s start with another code example now function second and the only purpose of this is just to show that there is this little flag called ustrick there’s a strict mode in javascript we’re not going to go into it much but this will change how the this keyword is bound and so if you have ustrict turned on and you try the same thing that we just did here let me comment all this out using that alt shift a technique and we essentially do the same thing here where we go console.log and then um second equals global let’s see if we get what we think we’re going to get from the first time around false all right well i happen to know that it will equal undefined and that is a true statement what gets returned from this when we use you strict an undefined value it gets bound to essentially nothing all right so just keep that in the back your mind this the rules around binding to this keyword change depending on the context in this case the context is you strict it will fundamentally change how it works all right so with that out of the way let’s move on to the next example here let my object equal and i’ll create a property called value and set that to my object and then i’m going to use this um use create a global variable called value and i’m going to set it on the global object by doing this global.value at this point i’ve created a new property on the global on the global object and i’m going to call this global object all right again in node this has special significance if you’re doing web development it’s actually window and we’ll look at that here in just a little bit all right so now let’s go function third and we’ll return this dot value and then we’ll do a console.log third so by default what do you think will get printed out will we print out the value of the global object which i set to the string global object or the value of my object which is set to my object well hopefully based on what we learned in this first example you already know where i’m going with this and because we called third from the global namespace when we reference the this keyword it’s referencing this global variable so when we grab the value property it’s grabbing the value property of the global variable thus printing out global object let me show you that there are other ways to actually invoke the third function and we can control the binding of this keyword like so so here we’re going to console.log and then i’m going to call third but i’m not going to use the method invocation operator i’m going to use the call method or the call function of the third function all right so it has a built-in method called call and there i can pass in my object and this is how i will bind the this value to my object so the value will be pulled from my object not from the global variable so let’s save that here let me actually comment this one out save it and let’s run it okay hopefully that makes sense there’s another similar function called apply and they’re very similar um and in this context won’t be obvious how they’re different because i don’t have any additional properties to send in or rather input variables to the third function so if i had something like a name i would use then like called on you know bob but this can also take an array here in the apply which could include bob so just do this see what we get i haven’t tried this beforehand so yeah object bob okay now just out of curiosity what would happen if we did this probably nothing at all just be blank yeah object undefined alright global object with the word undefined next to it okay so hopefully that makes sense what i just added on there that’s really to illustrate the difference between call and apply and so if i had multiple input parameters in the call i would just add them on there if i had multiples i could add them on inside of an array all right that’s the only difference okay but let me just kind of annotate this and talk through it just for a moment so just to kind of recap this this keyword depends on how a function is called and an object can be passed as the first argument to call or apply and the this keyword will be bound to it like we did here in lines number 54 and 55 all right and so just to kind of remind you about this i’m going to go ahead and say this property is set on the global object and then kind of works inside of here this will return something different depending on how we call this method right and then i just want to add this little annotation here as well both call and apply allow you to explicitly set what you want to represent this or how we want to refine this the difference is how the additional arguments are passed in like i show you here okay so when it comes to calling a method of an object the call site will be the object itself and all of its properties are available to this in fact if we take a look back here that’s what happened that’s how i did this and why i use this.make and this dot model again when it comes to calling a method of an object in this case print description the call site in this case car dot print description will be the object itself and all of its properties like make model and year are available to this inner function only when i use this keyword because this represents this context all right because i’m calling print description using the car object all right so to call the function i would use the object reference that object reference car gets bound to this keyword so to further illustrate this idea let’s do this i’m going to actually select everything we’ve done from here down [Music] and shift alt in a and so let’s go function fifth and uh here i’m gonna go console.log and this dot first name [Music] and a space and this dot last name and hopefully this will make a lot more sense all right so now what i want to do is create two objects so uh let customer1 equals and they’ll go first name colon bob last name colon tabor and then i’m going to create a print property that’s going to point to the fifth function like so all right and i’m going to copy this and just duplicate it i’ll make this customer 2. call this richard bowen [Music] all right and then finally we’ll go um customer two dot print customer one dot print all right so now look at how this works what is the context how do i call the print method that’s pointed to fifth well in this first case i’m using the object if it’ll let me get in there object customer 2 that is the context we’re going to bind this keyword to customer 2 because i’m calling it as a property of customer two i’m going to bind next in line number 85 the this keyword of the print method to customer one so let’s go ahead and so to me this example is really interesting because the call site is the object’s reference to the function and this keyword can be used to reference the various properties of the object that was used to call the function so it becomes an interesting and elegant way to essentially pass values into a function without defining a bunch of input parameters to the function itself all right so now what i want to do is kind of stop working with node for a little bit and look at this keyword in the context of a web page so i’ve created a new this dash keyword dot html i can use the term doc you can see that when i type in the word doc it’s an emmet abbreviation if you’re not familiar with emmit just search for it online it’s basically basically a shorthand um syntax for i guess you could say for snippets for code editors right so when i hit enter on the keyboard it kind of creates this bam this whole document outline for me and um it has some replaceable areas like the device width and the initial scale and the content and all that business i don’t want to change any of that stuff what i do want to do is add a script section here near the bottom for reasons i’ll talk about in another video and then what i want to do is above that create just a simple button so here we go button and inside the button i’m going to say hey click me and then i’m going to set a on click equal and we’ll come back to that in just a moment here i’m going to actually create a function that i want to call whenever the button is clicked so function and i’ll give it a name click handler like so and inside of here i’m going to go first of all i’m going to allow something to be passed in i’m going to allow uh a value to be passed in and then i’m gonna print out whatever that is to the console so console.log arg all right now we’ll come back to this in just a moment i’m gonna leave a space and go console.log this all right and then in here i’m going to say the button on click equals click handler so i’m going to call the click handler i’m going to pass in this this keyword all right so if all goes well here i should just be able to right click on this and say reveal an explorer and then when it’s in the windows explorer i can just like hit the enter key on the keyboard to actually open it up in my default browser and what i want to do is i want to use the f12 tools in an edge i’ll bring up this little window at the bottom here and i want to look at logs so make sure that you’re on the console tab and select the logs sub tab now click the click me button and we’ll see the results of both of our console.logs in the first case what we get back is the this that was passed in as arg and printed out directly to screen and so in this case the this keyword will reference this entire element all right so let’s take a look at that again here you can see how button on it gives me the whole thing so i can do something like this which if you’re familiar with web development should not blow you away i should be able to do arg.inner text and if you’re familiar with web development at all you would expect to see what there let’s refresh the page click the click me button again and you see click me all right that’s the inner text of that button so i’m able to get to all the properties of this button but the key here is that that this keyword represents this entire button and i’m passing this keyword in so that i can look at this entire button inspect it grab a property out but when i use this keyword inside of my click handler function what do i get i get the global object now we said in node the global object the name of it is global in a web browser the global object’s name is window so i can actually just like use this little arrow this little carrot chevron right next to object window and it will allow me to view all of the objects the child objects of the window and there are literally maybe if not hundreds definitely dozens of different objects and properties uh that we can that we can inspect and and change programmatically we’ll come back to some of those ideas a little bit later but basically the takeaway from this is that whenever code is called from an inline on event like on click on event handler it’s this is set to the dom element on which that listener is defined that’s why we got back this entire button including the text including the closing button tag but we’ve not taken any special steps to bind this inside of this function we’ve defined here the click handler so it defaults to the global object the window object okay so the moral of the story is that what the this keyword is bound to is not always obvious it takes a bit of detective work more so than this keyword and other programming languages but it has to do with how a given function is called and the site from which it is called so in this case this keyword is used at the call site is at this element level in this case the this keyword is used at the global level all right and that will change the value of this and what it’s bound to but by default functions that are called using the method invocation operators alone will use the context in which the call is made so if the call is made in the global context then this keyword will be bound to the global object if the call is made in an object then like we saw here near the end the this keyword will be bound to that particular object and we were able to use it to grab out the values of the given object all right and you can take control of what the this keyword is bound to by calling it using either a call or the apply method of a given function and we talked about what they do and how they’re different and finally whenever you use them in a use of this keyword in a browser once again what this is bound to depends on how it’s being called and who is calling it alright so hopefully that clears up what this keyword is i’ve given you a lot of examples i’ve tried to speak a little bit more slowly and and hopefully you can wrap your mind around what this actually is and um hopefully from this point on you’ll be able to identify uh what this is in your code all right hopefully that helps all right you’re doing great hang in there we’re getting close to being more we’re more than halfway done and you’re doing awesome see you in the next video thanks in this lesson i’ll briefly demonstrate how to use destructuring which is a fairly new technique in javascript for unpacking values from arrays into individual variables or i guess into other array elements of a different array but you can also use it to unpack properties from objects again into other distinct variables or a different object so use this term unpack you’ll see what i mean here in just a moment let’s start by creating a new file called d structure ring dot js all right and the first thing i’m going to do is create a bunch of loose variables here just a b c d e will wind up using most of these at some point and then i’m going to borrow that array that we created a while back maybe recognize some of these names all right and then next up uh let’s start by just destructuring this names array into um a a set of variables so i’m going to start off by using names which i know is an array and i’m going to use this bracket syntax and say take the first element of the names array and stick it in a whoops whoops whoops there we go an a take the next element stick it in b you know c d and i could even change the order instead of um [Music] d and e i’ll go e and then d all right and so let’s just do um console.log a console.log b and then console.log d because that’s a little bit more interesting now we’ll just go ahead and print out c as well why not and then we’ll go e all right and so here we’ll go node d structuring all right so take a look at what happened we have this array we destructured it down to a set of individual variables and we start off with a representing david the first element of the original array eddie the second element of the original array alex because we’re grabbing them off in sequence i did something a little bit interesting here and so much that i switched e and d so that e will represent michael and d will represent sammy when i print them out going back to alphabetical order d then e sami is first then michael all right so but the key to this example is that i’ve taken everything inside of an array and using this style syntax i’ve destructured it down to individual variables all right so that’s just one example there’s some other interesting ways to to work with this let’s uh let’s just go here i’m going to take all this alt shift a comment it up and the next example i’ll do a let others so i’m adding an additional variable here in addition to the other ones that we created originally and here i’ll go um a b and i’m going to use this weird syntax of dot dot dot others all right equal names so now um console.log a console log b and then let’s see what gets put out into others all right so this time a is from david b is eddie just like before but this time i said basically everything else just go ahead and stick them in a new array called others all right so that’s what we see here printed out from line 21 we get this array uh representation in our console.log including alex michael and sami together all right so that’s just another twist we can basically take some elements one by one we can then also kind of combine together entire groups of elements together let’s move on to another interesting twist on destructuring so in this third case what i want to do is actually work with an object and so whenever you’re working with object in objects and you’re destructuring out one object into variables or even into another object it’s really like a form of projection if you’re coming from other programming languages grabbing out the parts that i want of the original object and putting them into a new object with a different shape all right without having to take all the contents of the original object so i may only want one or two properties where the original has 10 or 20 properties so here let’s start off with just saying let year and model then i’m going to start off with car equals but i’ll get rid of that here pretty soon we’ll start with let car equal but it won’t matter because we’re going to remove that and i’m just going to create a typical old object um like let’s say it’s bmw the model will be a 745li year will be 10. the value will be 5 000. all right and in order to destructure this what i’m going to do is actually remove this and say hey i want to take the year and the model and put that into a new object of its own and then what i’m going to do is wrap this whole thing in a set of parentheses and then an end of line character like so so now we’ll do console.log here that’ll be the value here that i’m pulling out and my model it’ll be that value there that i’m pulling from the original object and printing it out so let’s see what we get all right so 2010 from line 34 and the 745li from line number 35. all right so that’s just some examples of destructuring um pretty simple concept it really is just a compact syntax that helps to clean up code whenever you’re trying to map from one data structure into another or into a set of variables and that’s all that it is alright so hopefully that made sense in the next video thanks another new feature of javascript allows you to create better literal strings through the use of templates so the term template literal is a kind of oxymoron parts of the string will be literal and parts will be templatized they’ll be variable based on an expression and so you can inject in other values variables or you can actually run entire expressions and we’ll see the use of a ternary operator in just a moment let’s start off pretty simple begin by creating a new file called this template literal [Music] literals.js inside of here i’ll do something really simple uh let name equal bob all right that’s not the template literal this will be console.log and now i want to use the backtick characters usually over the tilde if you’re not familiar with that region of your keyboard it’s usually right next to the number one two three one right next to the number one you’ll have to hold down the shift key to get to it so there’s one back tick whoops i’m sorry you’ll you don’t need to shift the back tick key all right usually above the tab key on your keyboard and so inside of there i’m going to use hi and then whenever i want to add something variable that will get kind of injected in from the outside it’ll be interpolated from outside of this i’m going to use the curly braces and right before the curly brace i’m using the dollar sign character you can see that the syntax highlighting in visual studio code changes the color of this to this bright blue color that’s cool and so then i can just say hey i want to use the name variable inside of there like so okay so we should be able to do something like a node template literals like so and i get high bob awesome so um the other cool thing about temple literals is that they will allow you to create multi-line strings now before this you would have to do a lot of using the append operator and so on but in this case you can do something like and i’m just going to copy and paste this because i want to type all this out you can see here that i start my template literal with a backtick and i end it with a back tick down here at the bottom so i’m setting this sentence or sentences actually this paragraph equal to this whole string and i’ve split it up on multiple lines and there’s no append character or anything like that what i can do is console.log sentence and the neat thing too at least from what i’m concerned is that it preserves the indentation level and the line feed character so you know i could do something a little more i guess artistic here come on let’s do this just with spaces like that like that and it preserves that indentation level that i have pretty neat right all right and then the other cool thing is that you can do anything inside of the expression interpolation area that you can do in a normal expression so and let me comment all this stuff out control i’m sorry alt shift a and here i’m going to create a function real super simple function get reason count just a very pithy silly idea here and i’m going to hard code this to return the value 1 all right and i’ll change it a little bit later so you can see the difference here but i’m going to create a variable called interpolation interpolation equals i’ll use the backtick character give me dollar sign curly braces we’ll come back to those in a minute to try this all right inside of here make some space for myself i can create any expression i’m going to use the ternary operator and so i’m going to say hey if get reason count just because i wanted to make things a little bit more interesting so i’m actually calling a function if it is equal to 1. and here’s where the ternary operator comes in i’ll say one good reason otherwise a few reasons all right and this is starting to pop over out of the viewable area but hopefully you can kind of keep track of using this syntax coloring you can see where the expression interpolation begins and ends inside of that here i’m going to evaluate the call to get reason count and if it’s equal to 1 i’m going to inject that part of the string in here otherwise i’ll inject this part of the string inside of my template literal and now i guess the only thing left to do is just a console.log interpolation like so let’s go ahead and actually run this so give me one good reason to try this well maybe we should try two give me a few reasons to try this all right so you can and i see the need for this all the time especially in web development where you may have one item in your shopping cart or two items in your shopping cart to change up the the string that gets outputted to for the end user based on a quantity all right and probably other good uses of that as well so string template literals are a nice addition to the javascript language here again they can make your code more compact and readable allowing you to do some interesting things in line that would require a lot of appending of strings previously all right so doing great let’s continue on see in the next video thanks regular expressions allow you to create a pattern to determine if a given string matches that pattern that you created regular expressions or they’re often just referred to as regex or regex are not exclusive to javascript they’ve been around forever they can be used in just about every programming language and i absolutely hate talking about them because they make my head hurt i’ve not committed the syntax of regular expressions to memory and so pretty much creating a pattern to find something is hard for me and i’ve developed a few little crutches through the years so that i can you know approximate or fake my way through the usage of regex and i suspect you’ll probably find yourself doing that as well unless you’re one of those really annoying people that just commit to learning regex inside and out and then you know can impress people at parties based on that knowledge so um i i try everything i can do to avoid memorizing it or learning the syntax usually if it’s something simple like making sure that a string matches the pattern of a phone number a zip code some something that’s fairly common especially with data in the united states i can usually find a good example of what i’m looking for online using a search engine or stack overflow but if it’s something custom for the given project i’m working on then i have to go and relearn just enough regex to get through that project and then i tried to purge it from my memory again so i’m going to show you where to go how to find the answers and and cobble together your own little regular expression but i’m not going to pretend like you’re you should go out and memorize any of this i know people have done it but but i usually wind up hating those people because they’re smug know-it-alls but i digress let’s just take a super simple regic example and use it in javascript so i’m going to start by creating a new javascript file called regex.js and here we’re going to say i’m going to create a simple variable called pattern and you can create a regex pattern by beginning and ending with a forward slash so in this case i’m just going to say hey search for this pattern where there are the exactly these three characters x y and z all right super super simple pattern you would almost never use something this simple unless you were looking for specifically the letters x y and z inside of some long string that you want to search through or a series of strings all right but there’s my pattern and so before we get started in earnest let’s just say hey what are you really first of all um i want to print it out and then i want to console.log see if we’re working with a new data type or is this just a data type that we already know so let’s go um node regex and uh looks like just attempting to print it out will just be a string representation of the pattern the type of the pattern is object okay so it’s a special built-in object to javascript we’ll talk about some of those global objects this is just a shortcut to creating one an instance of that global object for regex patterns okay so um here let’s continue on now and actually create some text that may or may not contain that pattern that we’ve defined so let value equal and we’ll go up this is x y z a test all right and so what we can do is there’s a couple of um of methods built into both strings and regular expressions that allow us to use regular expressions against a string or use our pattern against this value in this case this variable called value so we’ll start with the console.log and we’ll use our pattern dot and intellisense shows us there’s actually quite a few interesting things that we could use i’m going to keep this example simple and just say use the test method and so intellisense tells us that this will return a boolean value that indicates whether or not the pattern exists in a search string so what i’m going to pass in is the string i want to search through so in this case value and i would expect to get back a boolean a true or false if we can find xyz in that string so let’s save it i’m going to comment out these guys now i’m going to save it and i’m going to get back here and go node rejects and it is true we do find x y z our pattern inside of this string so let me comment that out the next thing that i might want to do is actually replace that pattern that we found in that string with some other string that’s pretty useful and i do that sort of thing a lot in software development this time i’m going to start with the string itself say value.replace and so that strings replace method has the ability for me to give it a um a pattern and then i also want to give it the value i want to replace if i find that pattern replace it with this string and i’ll just use the word just all right like so this is just a test so i’ve removed xyz and i replaced it with the word just by using the replace method of the string passing in the pattern and the word okay there are a couple of other things those are the two that i find myself using most often here you can do something a little more interesting i guess log value.match and this match function will return back an object that it gives some information about what the string was what the pattern was if it was found what the indexes in the string like if you were to split it up uh into individual characters at what point in the string would we find an instance of that pattern match so here we’re going to pass in uh the pattern itself so i’ll save that and you can see it gives me back this this array with the pattern we’re searching for the index where we can find it so i think zero is t so zero one two three four five six seven and eight so the x the beginning of that pattern is found at the ninth character uh index uh eight oh i guess it would be seventh character ninth character index eight right so um at any rate and then the original input was the entire string itself so we can actually modify this or you know actually grab that object out and work with it individually so value dot match pattern now that i have that array that we saw down here i can grab an individual part of it so console.log and here i’m going to go match dot index so just shows you how to get an individual part of it so here i can grab the index itself and i could use that to do some sort of custom replacement logic if i wanted to do that i’m not sure i would ever want to do that okay so now this comes to the part where i teach you how to cheat and if you really want to cheat you go out to your favorite search engine and you type in something like zip code regex and then if you’re lucky bing will pop it up to the top uh whether it be from stack overflow or just gives you a nice little usage example right there in line that’s a little dangerous because you don’t know if this particular example was uh voted up or down you might want to go and actually search through the comments and see the one that gets the most up votes and the selected answer and the one that doesn’t cause any argument in the community the other way is to go and kind of trudge through this yourself by looking at this page that and there’s plenty of references out there i prefer the developer.mozilla.org website personally i think their documentation is awesome and here you can learn about the various special characters and regular expressions and try to cobble together your own regular expression to find what you’re looking for but that’s all you’re going to get out of me that’s all i can tell you about regex because i’m not a big fan of it but anyway just to recap what we talked about in this video you can create a regular expression um literal with forward slashes you can use the regex’s test method passing in a string to see if that pattern exists in that string you can use the match method to find more details about the match you can use the replace method of the string to replace a given match with some other string like we did when we replaced xyz with the word just and then like i just showed you here at the end i showed you how to cheat you already know this look online whenever you need regex whenever you need regex help okay so let’s continue on we’ll see in the next video thanks up to now we’ve looked at a number of types can you remember them off the top of your head we looked at string number boolean object undefined and function as its own type and there are a couple of others that we haven’t talked about yet we’ll talk about null later and then there’s symbol which is new uh in the latest version of javascript probably won’t talk about that in this course but um what i wanted to point out though when we were using string in particular but this is true of the other of some of the other types that we worked with it seems to have some methods that are available to it to do some interesting things so for example whenever we looked at uh regular expressions and let me just create a new file here called natives.js whenever we looked at the the regular expression lesson we did something like value which is a string set to this literal string this is x y z a test and we did value dot replace well how is it that this value has this dot replace method we really never address that how is it something like a string can have a method after all we said that methods are really just functions that are defined inside of an object so that would make a string an object right or no but a string is a string how can that be well actually both of those are true statements the fact is that the types we’ve been looking at so far like especially string and boolean and number are known as primitive types these primitive types that have corresponding built-ins or natives that are functions that return objects with a bunch of cool methods that are added to them by javascript so behind the scenes javascript does something interesting it the javascript compiler will coerce your primitive in this case primitive string into an object that’s returned from a native string function with all kinds of cool stringy type functionality included so actually although we haven’t demonstrated this yet you could create a string using the actual string function to do something like this and let me comment this stuff out here and so notice what we did here let string equal new then here’s our function that built-in function string notice that has a capital s we’ll talk about that in a moment all right and then if we were to save this and then um let’s go ahead and get down here and type in node natives it works well kind of works almost exactly like a normal string we’ll get to that in just a moment so uh before i address that specifically i’m going to work with strings in this particular video and with the string capital s string function the built-in the native string but what i’m about to say about strings is true whether we’re talking about numbers or booleans or other other primitives that have an equivalent uh native associated with it all right so i want you to notice a couple of things and we’ll work through this first of all this starts out just like any other variable that we’re assigning to a string except we use this new keyword and i’m going to explain what the new keyword means in the very next lesson when we talk about constructors but basically this is what creates a constructor call to this function and then here we are calling a string function capital or uppercase s in string but isn’t that bad form didn’t you didn’t you say bob that we should create our methods with uh camel casing and so string should start with a lowercase s uh actually this is a special situation it’s still a convention indicating that this is a function that should be called using a constructor call again more about that in the very next lesson so you’ll get a part two to this but just keep that in the back your mind we’ll come back to it all right so whenever we run this as you can see here when we ran node natives we didn’t get an actual a literal string output instead we got basically an object that has a string property and a value set to howdy we actually need to call a method on this native that’s returned from the string function to convert it into a primitive string for the proper display inside of a console.log so we’ll need to do something like um i’ll just comment this out and we’ll go to string like so and now there we go we grab uh we convert that native that object return from our native string function back into a primitive string and then display it on screen okay so and while we’re looking at things here um just out of curiosity let’s go console.log and then go type of my string what would you expect to see here well it is a type of object all right so again what’s going on here is that these built-in native types provide extra functionality like this tostring method like this replace uh method and others that we’ll look at in other lessons um and they provide this extra functionality to their corresponding primitive types and so just real quick here is a list of those built-ins those natives all right so it includes kind of corresponding to the primitive string lowercase s and string number boolean there’s also an object a function in a symbol and then there are built-in natives that do not have primitive versions um the primitive version as you know of array is object and the same with regular expressions here regex but it does provide this native built-in with extra functionality for our arrays so the same kind of thing happens it’s just not with directly back to a primitive it’s to an object but it still works with any time we’re working with arrays and then there are some other built-in natives that provide foundational data types i guess you can say uh for important features but are essentially just objects whose methods implement a lot of logic uh for their features so things like the date function and the error function we’ll look at these a little bit later but in this lesson i want to focus solely on the relationship between primitives and built-ins so whenever we do something like this and let me just copy and paste some more code in here so here we’re creating a literal string and then on this literal string i’m going to call this method to lower case behind the scenes what’s happening is that javascript’s compiler is coercing is wrapping it’s boxing that primitive string my primitive into a built-in native equivalent in order to provide that rich set of methods that transform the string in this case to all lower case letters instead of all uppercase so if javascript is coercing wrapping boxing our primitive into this built-in native equivalent then what happens whenever we need to get a value back out of it well the javascript compiler will do the opposite it will unbox that object back into a primitive without you having to do anything special it manages all on its own so in this case let’s just uh kind of see what what happens here just out of curiosity let’s get the type of here we’ll put the type up there all right and we’ll see that when we run this let me make sure there’s nothing else here let me comment all this stuff out too at the very top of that file all right so now let me save that and we can see that it treats this literal string as a string here in line 31 then in line 32 it does that unboxing thing that we talked about to take string make it into an object so that we can call the two lowercase method on it and then what do we get back well at the point when we attempt to find out what the type of my primitive is it already has for our purposes essentially unboxed it back into just a primitive string all right so it’s recommended that you stick with with using the primitive and you allow javascript to do its magic the compilers can do this sort of thing without breaking a sweat so don’t worry about all this boxing and unboxing and the pro its impact on performance but but let’s suppose that just for the sake of argument that you wanted to start out with a built-in native and you want to explicitly convert that built-in native version of a string into a primitive string how would you go about doing that well let’s take a quick example and let’s go ahead and move away from strings just to numbers but the same idea will apply no matter what so i’m going to comment all that out let’s go let my number equals new number notice capital n or uppercase n in number and then in the constructor argument we’ll pass in the actual value that we want to set that number to all right so at this point let’s do a console.log and let’s find out what the type of number my number is have any guesses on what it will be let’s go ahead and stop right there and let’s make sure we understand it’s a type object at this point now i want to take it out of that built-in native and i want to grab just the value of my number out and put it into a primitive so here we go let my primitive i’ll just reuse that variable name here equals my number dot and then to grab the value out regardless of whether we’re working with string number boolean whatever the case might be we’ll use this method on this object called value of so the value of method and now we should do a console.log my primitive actually we know what the value will be what’s more interesting is the type of so now let’s run that and so here in line number 36 we’re going to get it’s an object but we use value of to retrieve the actual value of our built-in native object into a regular number and we print that out in line number 38 okay so to recap the point of this lesson is to explain what these functions are that have the same name as our primitive types but with an uppercase letter they are built-in native functions that are intended to be constructor called we’ll learn about that in the next lesson and the javascript compiler uses these functions to return an object that supports lots of rich features to each primitive data type and we’ll see those in upcoming lessons but the javascript compiler will box and unbox your primitive types into these built-in native equivalents as needed and will do so without any help from you and we’ll do it all behind the scenes and you can explicitly create instances of these objects and then use the value of method like we saw here just a moment ago to convert them into their primitive equivalence but it’s not really necessary so you know what’s this new keyword all about and what’s this uppercase letter in this function name all about well i’m going to explain that in the very next lesson we’ll see there thanks so previously we saw how to create an object literal using this style of syntax and you’ll note that i’ve already created a file called constructors.js go ahead and take a moment to create that yourself if you want to follow along i’m just going to paste in the car that uh the literal car that we created in a previous lesson here with the make model and the year property uh set to bmw 745 li and 2010 respectively now there’s actually another technique for creating an object and that’s through the use of what are called constructor functions so let me go ahead now comment this out and then let me go and create a new function and i’m gonna name a car and it’ll have some input parameters uh one for each of the properties that i want to initialize upon the creation of the object that gets returned from this function so make model and year and then we’re simply going to say hey the object that gets returned set its make property to the make input prep parameter that was passed in as the first input parameter and you’re going to add a model property to that object and you’re going to set it equal to the model parameter that was passed in and then you probably guess what this next line of code will do same thing with year right and most importantly whenever you’re creating an object using this this function it requires the new keyword so let my car equals a new car with a capital c did you notice that i named my function with a capital c car i’ll explain that in just a moment and intellisense tells me that it requires three input parameters into this function so here we’ll go uh bmw 745li 2010 all right and so what’s really going on here and let’s just go ahead console.log just to prove there’s nothing up my sleeve here my car and here we’re going to go uh node constructors and there you go we get a car object that has the properties make model and year populated all right so what’s going on here is that the new keyword creates an empty object calling the function in this case car it will take that empty object as the this remember our discussion about how the this keyword gets bound to the context from which it’s called well in that case that new object gets kind of becomes the context for this function call and so this empty object starts receiving new properties on lines 8 9 and 10 with new values set to those new properties what gets returned from this whole thing with the call to this function is an object with properties make modeling your already set all right so it’s important to remember that the functions themselves that we define here beginning line seven are not constructors although if you’re coming from another programming language like java or c-sharp you might be inclined to think in those terms because that’s how they work but rather in javascript it’s the new keyword in front of any normal function any function that makes it a constructor call all right it creates a uh a new empty object and it will pass it as the this to that function call that you make so the new keyword kind of elbows its way into the execution pardon me excuse me i need to get in here and it uh and it says to the function first before you execute i need to create an empty object and give that to you into this so it’s bound so this is bound to this new empty object and then it says okay now you can continue to do whatever you were going to do now the function itself could ignore that new empty object or it could use it like we have an 8 9 and 10 here all right so just to kind of prove that let me go ahead and comment all that out and let’s create a function my function and i’ll just do something simple like hey uh i am a simple function [Music] right and then we’re gonna go var my function equals new my function and then we’re going to go console.log type of my function [Music] or actually let’s go lowercase m or my function i’ve got some things wrong here like there we go that’s what i want to do and um so let’s all kinds of problems with that line of code but i caught them before i executed it so that’s good all right so you can see here in line number 21 we are creating a new empty object and then calling my function my function executes but not before a new empty object is kind of passed to it into this now this is not used in the body of my function so it’s returned back to this variable of the same name but with a lowercase m probably should have chose a different name if that causes any confusion i apologize just remember lowercase m my function is different than uppercase and my function in this particular case but when we take a look at the type of my function it is object all right and so at this point you know it’s an object so you can’t really do anything interesting with it it’s no longer a function so you can’t do that in fact here let me just um kind of copy and paste this little note i put to myself in my notes here you can’t really do anything with this particular object it’s certainly not a function reference anymore it used the function as a constructor but the constructor function didn’t really do anything to populate the properties of it and you know this will not actually do anything in fact if anything let’s just see what happens if we run this yeah we get an exception here that my function is not a function so we really can’t we can’t do that all right hopefully that makes sense the right reasons why but the only thing you can do with you know what gets returned here my function is that you can attach properties and methods to that empty object which is kind of the point of the new keyword entirely all right so what about this upper case first letter convention i said that it was a convention what’s a convention what is this particular convention you know specifically well you’re basically saying my intent is that this function be called using the new keyword that’s what the convention is basically i am a function but i should be called uh i should be used as a constructor so you should only use a new keyword on me and i’m expecting an empty object be passed to me so i can set some properties on it or maybe add some methods as the case might be all right so just keep in mind that in javascript what makes a constructor function has nothing to do with the function declaration itself but rather how the function is being called it must be called using the new keyword in order to be a constructor function so in the previous lesson we learned about the built-in native constructor functions that return objects with properties and methods to wrap around the primitive types and give them essentially superpowers giving them new properties and methods that will operate on the primitive value new functional new functionality like the two uppercase uh the two lowercase the length property and others that we’ll learn about but that’s why they’re defined as uppercase s in string uppercase n in number uppercase b and boolean and so on that’s why you can explicitly create one of those built-in natives if you use the new keyword like we demonstrated in that previous video so hopefully that all makes sense uh if nothing else i hope you’re learning how javascript is all about functions first of all and secondly how you call a function really changes the the the meaning of the function and what it’s intended to be used for it changes even in some cases the functionality that’s defined inside of the function like in the case of this or perhaps changes the purpose of the function like we saw here um with the new keyword and calling into the function all right so doing great let’s continue on see in the next video thanks javascript has objects and we’ve seen how to create a literal object and we’ve seen how we can construct an object using a constructor function and the new keyword like in the previous video in some of the most popular programming languages you create an object using a pattern called a class or construct called a class in other words you create a class named car and then you create individual instances of the car class as individual separate objects now furthermore you can create specialized versions of one class borrowing all the properties of that parent class in the new child class so you have an original class and you say i want to inherit everything that that original class does in my new class and then you can extend it by adding properties and methods to it to make it a more specialized version of that original or parent class so to kind of extend the analogy here i may have a car class but i want to create a sports car class that extends the definition of just a normal car and it adds on things that make it sporty same thing with a minivan it’s just like a car it has some of the basic principles of a car but a minivan also has like number of passengers and cargo capacity things that make it unique a unique type of car all right and then i can create instances or objects based on that minivan or objects based on the sports car and those objects are both have similarities to a regular car but they have differences as well all right so that’s kind of the notion of of classes and inheritance and classes and inheritance are a foundational concept associated with object-oriented programming not sure if you’ve ever heard the term but it’s a pretty big deal among software developers so you might be asking yourself well first of all does javascript have classes well yes and no i mean in javascript you have objects and you can create an object and dynamically add properties and methods to it whenever you want to but objects are the focus in javascript in languages like c sharp and java and c plus you create a class and you add properties and methods to the class up front and they’re static in so much that they cannot be changed so you can’t be adding properties and method declarations to the object at run time i mean you can but it’s not the original intent of object oriented programming um [Music] they can’t be changed over the lifetime of any objects that are instances of that class so here in in object-oriented programming uh languages base languages like c-sharp and java classes are the focus javascript objects are the focus c-sharp java c plus classes are the focus the latest version of javascript does in fact have the concept of a class but it’s a weird little stop gap measure to help people that are trying to make the mental leap from an old language that they might be familiar with like c-sharp or java into the world of javascript to a dynamic object-based programming model so i talk about javascript classes in one of the upcoming lessons and we’ll get to that soon enough but i guess okay so javascript kind of supports classes kind of doesn’t support classes what about inheritance well here again javascript yes it kind of supports inheritance but not really the kind of inheritance from traditional object-oriented programming so in javascript you have something different called a prototype chain so let’s suppose that you define a literal object like our typical car example that we’ve seen so many times won’t even paste into screen you know what it looks like it has a make model in year property right and so you define this literal object like our typical car example you like the properties and the methods that you’ve already added to that object and you would like to use that car object as the basis for a new car object you’ll probably wind up changing some parts of the object’s definition maybe some new values and a few of the properties you might even add some new properties and methods to that new object and i’m going to demonstrate a technique that allows you to construct a new object based on an existing object here in just a moment but when you do that when you create a new object based on an old object something special happens in javascript there is a permanent link that’s created between those it the new object always knows who it inherited all those properties its original set of properties from how did it get created it always knows uh kind of the link between it and the prototype that came before it all right in other words the original object serves as a prototype for the new object and the new object is essentially chained to that prototype from that point on so in languages like c sharp and java and c plus those traditional object-oriented programming languages you create a class hierarchy where one class inherits from another class so whenever you create an instance of the child class there’s really nothing that’s linking that that instance of the child class back to the parent class so there’s nothing linking that child object back to the parent class definition so here again the focus is not on the relationship of individual objects that happen to be linked to each other and kind of have a brotherhood but rather more of a parent-child relationship in traditional object-oriented programming again the relationship between classes is the focus of object-oriented programming whereas in javascript it’s the relationship between uh between objects and how they’re chained together it’s a sub uh subtle but important distinction between javascript and other and traditional object-oriented programming languages so some people use the term javascript prototypal inheritance all right but i’ve tried to stay away from the term inheritance when talking about javascript because it might conjure up traditional object-oriented programming concepts that would mislead you whenever you’re considering how it all works in javascript one of my favorite favorite javascript authors kyle simpson called this style of object-based prototypal inheritance it calls it really objects linking to other objects or ulu o l o o objects linking to other objects and i really like that description and by the way i’m not sure one way is necessarily better than the other they’re different their pros and cons depending on what you’re trying to accomplish the given problem you’re trying to uh to solve so what i do want to do is have a better thorough understanding of how you know objects linking to other objects actually works and what are some of the ramifications of that so that’s what we’ll do in the rest of this video so you can see that i have a new file called prototypes.js and here i’m going to paste in my original car this looks an awful lot like the car literal that we’ve been creating object literal that we’ve been creating up to this point now i told you that there’s a way to create a new object based on an existing object and so let me do that we’re going to say hey let our new car equal capital o object dot create and then original car all right so this point if we do for example console.log car dot make for example so let’s um node prototypes okay so we have this new car and what it looks like at least at first glance it appears as though we have a new object called new car and the value of the original car has been copied in of the make property of the original car has been copied into the make property of the new car but that’s not exactly what’s going on here as we’ll we’ll talk about here in just a moment but at this point i have two objects i have the original car and i have the new car and i could do several things at this point with new car i could change the values of the existing properties that i have on new car i could add new properties to new car or new methods to the new car or i could delete the existing properties from new car all right but more interestingly i want to revisit something i said earlier about the relationship between the original car and the new car that there’s a link between the new object and its prototype its predecessor the original car and so if we do something like console.log and we say object dot get prototype of and inside of that method i’m going to say new car so tell me who the prototype of this object new car is and it’ll say it’s this object right here where the make is bmw the model 745li in the years 2010. all right so it’s pointing to this original car so let’s do this instead we can actually get a reference to my prototype get prototype of passing in new car and then i can do console.log my prototype dot make and so you can see here that i’m able to get back to that to the make property of the original car now there’s no way to really prove that because they both seem to have the same values right now but we’re going to push this a little bit further what happens if i were to add a property to the prototype in other words what happens if on original car i were to add a doors property like a doors count so if you remember all i need to do on an object to add a property is just go hey i just want a new property called doors so i do doors and then i’m going to create the value and say hey it’s for now let’s go console.log newcar.doors all right you can see that the new car gets this doors property and it seems to be copying that new property over but that’s really not true but we definitely see that there’s a link between the uh the new object and its prototype the original car but how do i know if the property is defined on the new object or on the prototype well here’s what we can do and so this is going to help us to kind of get to the bottom of this relationship right here we’re going to start with the original car and says do you have your own property does this property belong to you or are you essentially borrowing it from your predecessor so first of all it’s true that the original car has its own property called doors okay so console.log new car do you have your own property called doors and that’s false all right so kind of tying this all together and kind of explain what’s really going on here well whenever we attempt to get a property or call a method on an object javascript will go through a series of lookups to find the value or the definition of the property or the method in order to call it so after we created new car it had none of its own properties if we asked it for the value of one of its properties doing something like we did um here in line number nine it would find the prototype that new car links to and see that if it has its uh make property so we know that the new card does not have a property that we define on it called make but what about its prototype and yes the prototype the original car has a make property and it’s set to bmw okay but once we do something like this new car dot make equals audi all right so we are changing the property or we’re actually we’re creating a property on new car and we’re setting its value to audi at that point what happens is whenever we come down here and basically call the same essentially same line of code now in line 11 it’s saying hey new card you have a property called make and new car says yes i do now i have my own property called make and it’s set to the value audi all right so no longer do you have to continue and look at my prototype to find the property and its value you could look at me and find the property and its value all right so javascript doesn’t need to look at the prototype chain if the property is created and set on uh the new object that is essentially created from the prototype so if we ask for a property that’s not yet been defined so here we go let’s go here in line number 12. console.log new car dot whatever all right now think about this whatever property does not exist on new car whatever property does not exist on its prototype the original car so what happens next um well then javascript will traverse back and say hey original car what are you linked to and since we defined original car like this we’re linked back to type object actually it is the um the built-in native object function however the whatever property is not defined on that either so now what happens well finally javascript will do one final traversal asking the object built-in native object what its prototype is and by default it will return the primitive undefined so when we get to line number 12 in fact let’s go ahead and comment out just about everything else here i’m going to hit a there and we’ll get rid of all this just so we can kind of see what we’re doing here so at this point what happens we get undefined why because new car doesn’t have a whatever property we look back and the prototype original car doesn’t have whatever property it’s prototype object doesn’t have a whatever property and its prototype is undefined and that gets returned okay that’s the end of the chain so to speak and that my friends is basically how the prototype chain works in javascript you don’t have to use this you probably should know it although you could probably go your whole career and not really have to ever deal with it however this is fundamentally how all your objects work and why you get the undefined type returned when you attempt to access a property value that doesn’t exist so i tried to make this as simple as possible but this is a post-beginner topic in fact i was looking at some tutorials online and i saw that this was actually an advanced topic but if you kind of understand what we’re talking about here think about how far you’ve come in your javascript understanding to get to this point where you can kind of understand what’s going on that’s impressive so i would just recommend that you watch this again you take a look at a few other tutorials online you give it some time to sink in and you’ll probably leapfrog over a bunch of people who are trying to learn javascript but not really pushing themselves past the absolute basics you’re doing great hang in there we’re making great progress and we’re getting close to the end relatively close all right so we’ll see in the next video thanks in the previous lesson i said that javascript doesn’t have classes at least not in the traditional object-oriented programming sense nor did it have inheritance in the traditional object-oriented programming sense i explained how javascript is focused on objects and the linkage between objects that are based on objects we also looked at constructor functions that allow you to construct a new object from a function call but this really isn’t a class in the traditional object oriented sense either but technically javascript does actually now have classes or the notion of a class and it was introduced in the last version of javascript now javascript classes give you the impression that you’re working with something that resembles traditional object-oriented programming but in reality nothing has really changed javascript remains object focused and objects can still be prototypally prototyped prototype chain together i don’t know how to say it correctly javascript classes are what is termed syntactic sugar on top of the existing javascript object and prototype models that term syntactic sugar you’ll see that frequently in software development circles it’s programmer slang that means that they added a few keywords and structures in javascript but these merely map to existing features of javascript they don’t really add new features per se so the syntactic sugar might help those who are transitioning from more traditional programming languages to javascript but javascript purists are quick to point out that this new feature the class feature in javascript may do more harm than good because at the end of the day you still have to make the switch from classic or traditional object-oriented programming to a more object-based prototype inheritance if you want to use that term and if you’re working with prototypes you have to learn the things that we talked about in the previous lesson okay so in a nutshell let’s talk about what a class is and define a class it’s essentially a way to define and create objects and so just like there are function declarations and function expressions now there are class declarations and class expressions so let’s start off with just looking at a class declaration and so you do something like class car whereas an expression would be more like let car equal class and then whatever okay so fairly simple and hopefully straightforward it’s basically declaration you give it a name an expression is well it’s an expression so javascript classes can have a constructor function that gets called automatically whenever you use the new keyword so let’s go with the declaration version of this i’ll comment this out this expression all right so inside of the declaration let’s create a constructor function you have to use the term constructor then you can add any input parameters that are essentially going to map to properties that you’re going to add to a new instance of an object based on this class so here again you do something like make model and year and just like in the constructor functions that we learned about a couple of videos ago you still use the this keyword make it will make this dot model equals model this dot year equals year okay so you can see similarities here right and then uh to create a new instance of an object based on this class you would do let my car equals new car passing in you know bmw 745li and the year 2010. okay so again i want to make the point here that that word or that name of your constructor function in a class definition in javascript has to be named constructor in order for this to work and here you’re still using the new keyword new still creates an object instance it still passes it to the constructor function now in this case the name of the function is not car it’s the name is constructor but you’re passing input parameters into that constructor method and then using this this context it’s the new empty object that we’re attaching properties to and then initializing their value to the arguments that are passed into the constructor all right hopefully that all makes sense and it’s similar enough to what we’ve already learned that it kind of you can see where things are mapped again syntactic sugar on top of what already exists all right so you can also create methods on the class um in fact let me do it outside of the constructor method so here i want to create a print method [Music] and you know i can do something like console.log and then i’m going to go ahead and use our special sends string syntax interpolation syntax let’s make some space for myself here and i’ll say uh this dot make this model and um i’ll format it a little bit with some parentheses but inside we’ll go this dot here all right so here again now that i have an instance of my car class called my car i can call print like so and so let’s go um [Music] node classes and you can see i get the nicely formatted version of the information in my car class you’re calling the print method all right now beyond these basics you can actually approximate inheritance at least inheritance in the classic optic dorian programming sense so in our case let’s kind of go down here at the very bottom and i want to create class sports car and i have to use the keyword extends car all right so right off the bat when i do that and i create a new instance of sports car let’s do that so uh let my sports car equals new sports car now i don’t have a i don’t have a constructor function defined but when i use the open uh the open parenthesis notice that intellisense still sees that i have make model in year why is that because by extending sports car from car i still get the constructor method defined on car and i can still set the make model in the year so here let’s go um [Music] dodd whoops dodge viper and i don’t even know if there’s a 2011 version of it but i don’t know if they stopped making it or if they’re still making it i’m not even really sure but it doesn’t matter all right so um at this point and we can even call mysportscar dot print all right and now we get that print out here like so so we’re extending we’re borrowing the entire definition of our class and we are getting the constructor method defined in car we’re getting the print method to find a car but i can extend and push beyond the boundaries of the car’s definition by adding properties and methods so for example here let’s just add a quick method and i’m going to call it since it’s a sports car we’re going to create a method called rev engine which will be a unique printout of information so console.log and we’ll do something dot vroom goes the this dot model okay so now i can call my sports car dot rev engine and i get vroom goes the viper i guess i should have had a space right there all right now what if i were to do this i still have my car can i go my car rev engine let’s see nope can’t why because it says rev engine is not a function well it is a function it’s just not defined on the car class it’s defined on the car classes inherited child called sports car so you can’t access rev engine from the car class and you know what honestly there’s more to it than that um there are some advanced scenarios but that should be enough to show you what cla uh the class keyword and the extends keyword can do and how it operates and you can see the rough equivalence between what we did here and what we’ve done previously and hopefully you can kind of see that there’s a mapping in that ultimately what’s going on behind the scenes though is that we’re creating a sports car object and its prototype is car and we’re adding on a rev engine method but when we look up the constructor function when we look up the print method it’s still using prototypes behind the prototype chain behind the scene to manage all that it’s just javascript is kind of covering that up just a little bit with some different syntax okay so my personal opinion is that if you’re coming from a traditional object-oriented programming environment and you need to become productive very quickly because you have a looming deadline or whatever the case might be you might be better off trying something like typescript which was created by microsoft it gives you the feel of c-sharp and java more so than javascript will and it gives you more of that traditional object-oriented programming look and feel and ultimately it will transpile down to pure javascript kind of out of the context of this conversation just what you should do is go to typescriptlang.org and you can study up on it a little bit but it’s essentially a super type of javascript meaning anything you do in javascript will work in typescript but typescript gives you some extra features that will make it feel more like java or c-sharp if that’s something you need but most importantly if some of this doesn’t make sense the things that we’ve talked about here don’t beat yourself up about it again this is a feature that was added for specific demographic people coming from other programming languages it may not have been intended for somebody who is just starting to learn javascript so don’t feel like the pressure now to go out and learn traditional object-oriented programming before you can understand how to use class you don’t even need to understand this it’s just again something for a stop gap measure for people coming from another programming language um [Music] so it might not be immediately obvious to you in what situation you might find yourself using this and why you would prefer this over what we looked at in the previous lessons but at this point just focus on um the language the fact that these things exist the fact that they were added for a reason and the reason is to help somebody else maybe not you specifically somebody coming from a different background to make that transition to javascript and you know ultimately i think with a lot of the things that we’re talking about here their usefulness will reveal themselves to you later whenever you start programming and creating real applications with this language all right so uh you’re doing great just hang in there we’re making great progress um you know the fact of the matter is that learning is is iterative and if this is your first attempt to learning any programming language or your first attempt at learning javascript specifically no doubt you’re going to need to come back to some of the ideas that we talk about you know in the coming days weeks or months and you’ll continue to come back to some of these ideas over and over i mean i keep studying and kind of pushing in new directions coming back to studying the basics and then pushing a different direction and you have to do that in order for these ideas to fully sink in over time i mean i’ve been working with javascript almost my entire career and i’m still learning things so it’s just the nature of learning this sort of stuff there’s so many details and there’s only so much time in the day so don’t beat yourself up you’re doing great you’re taking great strides towards understanding javascript so hang in there we’re just kind of entering the home stretch now you’ve come so far just a little bit more and then you can honestly say that you’ve you’ve got a firm foundation of javascript to build on okay a little encouragement to get you over the hump here all right we’ll see in the next video thanks in the most recent version of javascript you can define a function using a shorthand syntax called arrow functions and arrow functions since they are just a shorthand syntax for creating a real function and functions are used everywhere in javascript as you know by now you might not be surprised to hear that there are many different ways that arrow functions are used in javascript and there are many different syntax variations to boot so what i want to do is start simple and i want to look at a few practical applications of arrow functions but we’ll start using them as frequently as possible from this point on and you’ll begin to see them pop up just about everywhere all right so you can see that i have a file called arrow functions.js that i’ve already created and i want to create my very first super simple arrow function so here we go i’m going to create a function called hi i’m going to set it equal to a set of empty parentheses what’s called the fat arrow operator so equal sign in a greater than symbol after it to kind of resemble a fat arrow i guess as opposed to a thin arrow which has absolutely no meaning in javascript this fat arrow then will point to a body defined by an opening closing curly brace and then we’ll do console.log howdy okay so far so good right one line of code an entire function declaration and we can just call hi so here we go let’s go um uh node arrow functions and we get a simple word howdy printed out okay that’s easy enough so let’s comment that out and move on to a slightly more interesting example um we can actually go let hi and inside of the open and closing parentheses we can accept an input parameter so what these really are instead of using you know the keyword function we just get rid of the keyword function but this remains and it allows us to define an input parameter name inside of or after the fat arrow and inside of the body i can go console.log we’ll use our our special backtick character and we’ll go howdy and then dollar sign open close and curly brace name add a few semicolons to the ends of some things here really probably don’t need this one per say now let’s call hi bop howdy bop okay so you can see that all we’re really doing here is just creating again a shortened version of a function and we don’t need the keyword function we just go ahead and start with the opening closing parenthesis to define the area where we can add input parameters the fat arrow points to the body of this of this arrow function and inside of there we can just do whatever we want to do just like we can in any normal function even reference input parameters like we’ve done here all right now up to this point we’ve just been kind of creating what i call void functions they don’t return anything but what if we need to use the return keyword let’s create a different version of this so we’re going to create add add equals here we go we’re going to allow this to take two input parameters a and b and we’ll just do something super simple we’ll hear once again but we will use the return keyword a plus b and now we can do console.log add seven three and we get 10 printed to screen okay can you see this same basic structure here we’re accepting two input parameters separated by a comma here we’re still referencing those in that body that we’ve defined using open and closing curly braces use the return keyword it’ll get returned to our method as a as a return value of our method call and here we’re just passing in numbers getting that value back and printing it to screen okay so far pretty easy stuff right now you might be wondering how could i ever use this sort of thing um what is its pertinence and so i think that one of the ways that i and uh see them using being used the most is whenever you need to run a function over each element of an array and so let’s use our let names equal and you’ll recognize these names once again okay this time we’re going to call the map method now this happens to be a a method defined on the array built-in native object that we learned about but we’ll talk about more of these helper methods built into the array built-in native object in an upcoming lesson but the map is a pretty cool one because what it allows us to do is to basically iterate through each element of an array and when we it iterates through it will actually allow us to call a function and this is a perfect spot for creating right inside of here one of our arrow functions so in this case let’s say you’re going to iterate through each element of names whoops i need to use the right word here names right and so here we’re going to create an arrow function that accepts a name and what we’ll do is to marry these two ideas together console.log and then howdy name all right and you can see basically in one line of code i was able to map each element of the array to our arrow function it passes in the name to the arrow function in the body of the arrow function now we can simply operate on it just like we were doing previously but as a result now for every single element of our array we’re getting a console.log with our little message okay pretty cool pretty cool let’s take this one step further as we continue to build on this idea let me grab this line again so i don’t have to retype that and then i’m going to say let i equal zero and actually let me just grab this line too because i want to do something a little bit more interesting because i want to show that you can actually do a little bit more in a single line like for example here i might increment the value of i and then use i here in the body but now i’m essentially doing you know two commands or two statements inside of the body and i’m not saying this will you’ll do this very often but it’s certainly possible all right so now let’s do uh save that get back to that so now david1 howdy eddie 2 howdy alex 3 howdy michael four all right all right let’s continue to build on this and now let’s use the return keyword kind of in the same doing the same sort of thing here so start with names uh in fact let’s go var transformed equals names.map and then i’m going to borrow some of these pieces here again i’m just going to borrow that except i’m not going to call console.log i’m just going to return that string see if we can get this all kind of lined up here okay so i’m re going to take every name in names and i’m going to return howdy plus the name and now i’ll do console.log the entire array that is going to be returned from this and saved into transformed so here we go whoops i got a spell log right all right and so you can see that what gets returned here because we’re returning multiple values they get added to essentially an array and now you can see on each element of the array is the literal string that we construct inside of this map function using an arrow function to do the construction and those individual names are now transformed and saved into a new array instead of just david eddy alex now it’s howdy david exclamation mark howdy eddie exclamation mark and so on all right so arrow functions are simple to create and they’re just a shorthand version of function expressions they really are useful whenever you’re working with functions on arrays like this map method that allows us to map each element of an array to one of our arrow functions and then basically execute that function against each element of the array and so we’ll see some other examples of this in some upcoming lessons all right pretty cool stuff all right we’ll continue on the next video we’ll see you there thanks designing a course can be challenging sometimes because when you finish a topic there’s a number of directions you can go after that topic but if you have an overarching idea that you want to get to eventually you’re going to have to kind of leave some important thoughts on the side and come back to them later and that’s really what’s going to happen in the next four or five lessons or so these are topics that could have easily been covered much earlier in the course but because i was trying to get somewhere i left those details off till now so hopefully you don’t mind that we’re going to circle back and fill in some of the or backfill some of the topics that we just didn’t cover in a lot of depth and the first that i want to talk about are these terms truthy and falsey which seem to be specific to javascript i haven’t seen them used in other programming languages maybe i just haven’t looked at the right programming language but basically it has to do with with evaluation so when you evaluate an expression like for example in an if statement or in a switch and you perform an evaluation of expressions sometimes they’re going to return absolute true or false one is greater than two that is false patently false and i would expect that i would get from that expression the false value but then there are other things that are not quite as obvious and there are rules in javascript that dictate whether an expression is truthy it’s it’s in and of itself it doesn’t look like it would be true but because of the rules of javascript it is true and things that are falsy doesn’t look like it would be false but based on the rules of javascript we’re going to call it false all right and so if you just don’t know what those are you’re going to maybe perform an a or evaluate an expression you’re going to get a true or a false and you’re going to be like what in the world’s going on there why is that true why is that false so i want to cover these cases and i hope you don’t mind that i’m just going to copy and paste these right in because it’s a pretty big chunk of code we’ll just look at these things but and the top these are things that are falsy well right off the bat line number one if you’re going to evaluate an expression if false that’s always going to be false that’s not really falsy it’s just false all right but then there are things like null if no well in and of itself no you know if we’re looking at this completely subjectively null is not true or false it’s it it doesn’t really have a connotation of being true or false it’s just null we’ll talk about null later however it’s considered by javascript to be a false c value same with undefined undefined is not good or bad it’s not true or false but javascript says that if something pops up and after evaluating expression it comes to undefined that’s going to be a false value the same with the number zero if an expression is evaluated and what’s output is the number zero that is a false c value it will return false in that expression same thing with not a number same thing with an empty string whether you use in lines six or seven single quotes or double quotes to define your your string now everything else is pretty much truthy in fact i don’t even know if there’s the notion of truthy in javascript it’s just everything is that’s not in falsie is essentially truthy but i gave you some examples here obviously just like if false is falsy if true is going to be truthy it’s just true but things like an empty object if you evaluate an expression and it returns an empty object for the purpose of of truthy and falsey it’s truthy same thing with an empty array same thing with a string that’s not empty so we saw empty strings are falsy but a string if you have something in it it’s truthy okay a new instance of an object is truthy even though there’s nothing associated with there’s no properties or methods doesn’t matter truthy same thing with any non-zero value whether it be an integer or a float which means values after the decimal point those are all truthy as is a constant in javascript called infinity whether positive or negative infinity all truthy values so here again if you ever come across something in an evaluation it returns an odd an odd value that doesn’t strictly return true or false it returns a null or undefined or not a number or a zero or an empty string falsely it’s going to the evaluate the evaluation of that expression will be false but everything else is pretty much going to return true okay that’s all i needed to say in this video hopefully that makes sense all right we’ll see in the next video thanks continuing the sentiment from the previous lesson where we’re kind of doing a roundup of topics that by all rights could have been discussed earlier in this course but we’re going to introduce them now i want to talk about the last of the data types that we’ll encounter the data type null so it basically null represents a variable that points to nothing but an object reference was expected in that case so just as a quick reminder you can create a variable and not set any value to it not initialize the value not set the value and in both cases or whenever we look at the actual value or the type of the value it is going to return undefined so the value of a because we’ve not set it to any value is undefined and the type of a is undefined all right but here that’s just a variable we didn’t set it to a primitive string number or boolean or anything of the sort all right let’s suppose that you actually are expecting the variable to hold a reference to an object so just to kind of copy a quick example from a previous lesson let me comment all this out and paste in this so here we have our regular expression example where we’re going to try and match a pattern x y z and we’re going to use the strings match method passing in the regular expression literal that we created in line five but this time there is no match there is no string x y z in my value variable so what is result set to well let’s see what we get in this case we get result is set to null all right well what is the type of results type of result all right this is going to require a little bit of explanation okay that’s the quirk with null it will actually return object not the primitive type null and that’s a known bug in javascript that will likely never be fixed because too much code on the internet depends on the fact that typeof null equals object is you know it’s it’s basically baked in and grandfathered at this point but by all rights if if javascript had been designed correctly from the start that would be null but hopefully you’ll get the idea there all right um but the interesting thing about getting a null result when we expected an object back is that we can do something like this and i’ll just copy and paste this instead of typing it all in we can check results and say are you you know and we’ll do the strict equality uh strict equality evaluation is result null and if it is then we can say well no no match was found xyz was not found in our value all right and so this can be extremely helpful whenever we’re uh building our applications all right so just to kind of recap null the primitive data type null is not zero it’s not undefined it’s not an empty string it simply means that you have a variable where an object reference was expected but it’s not set to any object reference it’s different than undefined right because undefined says i’m expecting to have a value but one was never set and it was expecting maybe a number string or boolean no no we’re expecting an object reference but we don’t have an object reference at this time uh set to our our variable okay so hopefully that makes sense and let’s continue on see there thanks it’s been quite a few lessons now since we’ve talked about the built-in native functions that return that return objects we saw at that time that there was a date constructor function and that date constructor function will return an object that allows us to work with dates and so i just wanted to take a brief look at what it can do and how you can actually work with date type information using the date object so let’s start off with a very simple case here i’m going to say hey let today equals new date and that will by default give us right now this date and time all right so what i can actually do is actually initialize that date object with a specific date using one of several different formats so i may want to like create a date that represents my birthday so i’m going to create a new date and i’m going to pass in and this is interesting right because if i look at intellisense it has an up and down arrow i can actually use the arrows on my keyboard and it will show me the various versions of constructors that are available with which to initialize the state objects so we could start off with something really simple and just kind of a full day like december 7 1969 and we’ll give it a time even at 7 0 1 23 just guessing at the actual minute and second of my birth i don’t really know exactly i know it was early in the morning that’s all so that’s one way to initialize uh the date but there’s a couple of other ways um and uh let’s just do like let bob equals date and there’s a file system date type that looks something like 1969 dash 12 for the month dash 07 and then t for time and then 0 7 because it’s you know on a 24 hour schedule colon um 01 colon 23 and that’s roughly about the same these these two will create the same basic time all right there’s also we could just kind of simplify things a little bit here using a different format just just give it um [Music] the year month base zero and day i think base zero as well though i haven’t really i’m not really entirely sure about that um and then what bob it’s kind of the same thing [Music] 11 6 and then 7 1 seven comma one comma twenty-three so i think these are about the same i may be off by one i forget if it’s zero based or one base but you can look that up fairly easily i’m not gonna use these but i just want to show you that they exist okay but we have here now today’s date and my original date my birth date and so what we can do is something interesting like get the time that’s elapsed between those two dates by just saying var elapsed time equals n equals today minus bob console.log elapsed time and what will get back to me is the number of milliseconds all right between those two between those two dates so this is the number of milliseconds and i could divide it out calculate the years the months the days the hours minutes and seconds if i wanted to all right so that’s one thing that i can do is determine the elapsed milliseconds between two dates you can also get parts of a given date so i can go console.log bob bob.getdate and um it returns seven what does that represent that represents the day of the week so in in this case monday would equal one and sunday would equal seven which seems a little backwards to me but hey that’s what you get when you create a language and you set null equal object and other kind of quirks like that moving on console. bob.gettime and this will be represented the time of day in our date object so that was uh the number of milliseconds and so that’s a little bit less useful but you can do other things and let me just paste in a bunch of these [Music] all in one shot you can get the month today hours minutes seconds and milliseconds and then there are also some additional date functions for things like conversion to utc or universal time code and local dates and times so converting back and forth between utc and local date time and that’s pretty much what you can do with the date object and so let’s continue on in the next video thanks previously when learning about built-in natives i explained how the string primitive is mapped to the string built-in native object and by boxing the string primitive into its equivalent string native object built-in string native object javascript therefore will supply us with a rich set of functions now in this lesson i want to demonstrate just a handful of these very useful string methods that are supplied to us by the string built-in native object and explain why they’re useful and i’m just going to pick the ones that i think are useful to at least they’ve been useful to me in the past but there’s a bunch more and i would just recommend that you use bing or your favorite search engine to search for javascript methods of string and you might find the mozilla developer site and it will give you a full listing of all the methods that you can get on that string object all right so first of all we’re going to need a few strings to work with just for fun and so i’m going to create some some different ones here two are quotes so the first quote is knowledge is power but enthusiasm pulls the switch and second is a famous quote from a good friend of ours do or do not there is no try and then finally a listing of random numbers that mean absolutely nothing and then you know one of the things that i didn’t really mention at the time is that um you realize that uh and i’ll just put this here you can even call these these methods on string literals like for example console.log bob loves you dot isn’t that crazy that you can just do dot on a string literal and call to uppercase well you certainly can so let’s see this message in all of his glory because i do in fact whoa it’s called strings i do in fact love you all right let’s move on all right so let’s um let’s use a couple of uh interesting interesting methods of string so we’re going to use the split method i’m just going to call set my split equal to the third this third one defined on line three with those variable with those values those numbers that are separated by commas and the split method will allow you to say hey every time you see a comma split that up and take the element in between the commas and add that to an element of a new array and so let’s go console.log my split and here we have an array with each value as a separate member of our separate element of that array pretty cool so you’ll do this a lot whenever you’re working with data and it comes to you in some sort of string like format you can split it out all right next up we can slice a string so let’s go let my slice equal first dot slice and then we give it the starting index and the ending index just to kind of pull out one little piece of the string and put it into its own variable so then we can do a console.log my slice so this first sentence we would count you know to the position 13 and then to position 18 and hopefully we’ll grab out that word and we do we grab out power same basic idea with the next one which is substring it’s just a tiny bit different so let my substitute equals first dot substring and here we’ll start with that same index but we’ll say just instead of giving you the end position just go over five five positions so this is the start and then this is the length that we want to pull from that from that first string it’s gonna go console.log my substitute and we get that same value there okay similar ideas between slice and substring moving on we want to return true or false if our string ends with a given string to compare it with so my ends with equals and we’ll use that second string that i created here try or do or do not there is no try and we’ll say hey does that string ends with true or false the word try period and then we’ll go console.log my ends with true great and um hey well and we can do sort of the same thing let my starts with equal second dot starts with and so this is just a way for me to say hey is this the string i was expecting does it have the values in it that i want so i can say does it end with this does it begin with this true or false all right so that’s true as well and then we can even say hey you know some someplace in the string [Music] does it include the sub string or the string there so is the word there used in that second string console.log whoops my include whoops there is no there all right how about capital t in there ah that’s true all right so it is case sensitive all right so let’s come in all these out interesting now let’s uh say let my repeat equals ha exclamation mark space dot repeat and the number of times i want that repeated is three and then let’s do a console.log my repeat and i get ha ha ha so the repeat method will repeat whatever the string is the number of times you tell it to and then we save that off to do its own variable and i think the last one we’re going to look at is a way to kind of clean up a string so let my trim equals and i’m going to put a bunch of spaces here and then in between i’m going to say this is bloated right and i want to clean it up a little bit so i’m going to go console.log and uh the first time through i’m just going to say trim.link this will give me the total number of characters in that string but then the second time i’m going to do what’s called chaining method chaining so my trim dot i’m going to use the trim method that should clean off all the empty spaces at the very beginning and the very end of my string and then i’m going to grab the length property so you can see dot trim dot length i’m able to since trim will return a string then i can call the next method or property on the string because i’m working again with the string type so i’m chaining those calls together to get the result the essentially the before and after so before i call trim we’re looking at 16 total characters here but when i call the trim and i get the length there’s only seven characters that means the word bloated should only be seven characters long and it is all right so those are some helpful string methods on the built-in native string function constructor function and we’ll do the same thing for array in the next video we’ll see there thanks since we gave strings methods the proper treatment i wanted to do the same for arrays so we’ll do that here and let me create a couple of arrays here i’ve got an array called names and an array called others i’ve got an array called lost and an array called fibonacci so the obvious difference is that here i’m working with strings here i’m working with numbers all right so we’re looking at methods that can be applied to arrays right so the first thing we can do is combine two arrays together so we can use the concat method so here i’m going to take the loss numbers and i’m going to concat them to the fibonacci numbers giving me a combined set of array values and here i’m going to go node array dash methods the name of the file i created and i get a long set a complete set where you can kind of see the division between the two sets now they’re all in one array okay seems like it might be helpful at some point otherwise we’d have to loop through and push or pop or i mean push uh elements of one array into the other array that might be a little bit uh a little bit of a cumbersome process you can also do something interesting like console.log and we can take combined or the combine well we don’t need that we can use fibonacci and what we’ll do is call join and i can say hey join all the elements of the array together and separate them with this string so i’m just going to use like a tilde here for no other reason than the fact that we just haven’t used utility yet and i think now we’ve used every character on the keyboard at least once all right so let’s uh save that and then run it all right and you can see that i just merely printed out the fibonacci numbers with a tilde join them together into a single string but they’re separated by a tilde now okay we’ve already talked about or demonstrated push and pop i don’t want to go back into those but there are essentially ways to add elements to the array or remove the last element from the array there’s some other ways to do that too for example here we’ve got a console.log we’ll take the loss numbers and we’ll call the shift method and what the shift method will do is re take one item off the front side of the array and it’ll return it back to us to print out but then if we go and look at the array we’ll see that it actually removed it so it’s essentially a pop but instead of working off the back end it works on the front end okay so let’s see that in action and we get that exact behavior that i described great we can do something called an unshift which is to add items to the front so it’s essentially just like a push except we’re going to add items to the front one or more items so here we go with the lost unshift and then we’re gonna say hey let’s add we can add one we can add two we can add a bunch of items right and so now we do console.log loss numbers oops we’ll see whoops what did i messed up i call it list instead of lost there we go and so now i’ve added the values 1 2 3 and 4 as new elements of my array and then it continues on with 8 15 16 23 and 42 okay let’s comment all these out moving on let’s um let’s find an element uh well first of all here uh console.log let’s take the names and reverse their order so first of all we’ll start with the original order and then we’ll tell it to reverse and we’ll print that out so originally david eddie alex michael but then we get michael alex eddie david all right furthermore what we can do is go console.log names.sort it’s a sort of method i got to use the method invocation operator so now when i run it we get the alphabetical order alex david eddie michael all right next up let’s um let’s see how you can identify where a given element is in an array by looking up its value using an index of method so here we’re going to go console.log and we’ll go others dot index of and i’m going to look up the element name mark all right and so let’s see where it’s at it should be the third element of the array so i’m going to go back up here to others 0 1 2 3. it’s at the third element so then i can go grab it okay how about we look at and find the last index of and let’s take those combined numbers remember those all those numbers we basically put them together let’s go the last index of the value one so here first of all let’s do this just so we can easily see what the current value of combined is and then we’ll say hey we’re going to search for the last time the value 1 appears in my list which array of the element is it at whoops what did i do this time i think it’s just combined right still not right ah because i commented it out now let’s try it there we go all right so you can see that our combine variable holds 48 15 16 23 42 1 1 2 3. so now i want to see what element is the last and it says it’s at the seventh element so zero one two three four five six seven zero based so the last index of one would be at seven so it’s useful if i’m looking through a large set of data and i want to find the last instance of a given value i can use last index of instead of index.which would give me the first index okay all right moving on you know previously we looked at the map function of an array i don’t want to belabor that because we’ve already seen it but we can do other interesting things too like we can create a filtered list so using arrow functions so var filter equals and we’ll go with com combine dot filter and now i’m going to give it an arrow function so for every number i’ll just say it’s x i can give it any input parameter name so here’s the body of my little arrow function if x is less than or equal to 15 then i want to return x all right and effectively what will happen is it’ll return only those numbers that match this expression so that when i do console.log filtered i should only see numbers that are less than or equal to 15 and so i get a filtered version of that of that combine array pretty cool and a good example of why you would want to use arrow functions similarly you can do something using a what’s called an iterable it’s a method called for each so this will go through each uh element of an array and inside of that i can then create an arrow function similar to things we’ve done in the past all right where i’m actually just going to for each element of the array go ahead and console.log this string and interpolate in the name that’s passed in pretty cool and then uh we can also do some checks so for example i can say hey can you tell me if every one of the values inside of my array match a certain condition so here i would go console.log and i’m going to take that filtered list that i just created here so this should contain all of the values that are less than 15 from my combine and here i’m just going to say hey let’s go filtered is every one of those values um and here’s where i’m going to create an arrow function so let’s call this num or every one of those numbers less than 10. true or false false why is that well i happen to know that there’s a at least a 15 in there maybe if we increase the number to something like 16 are all the numbers less than 16 well they better be because they wouldn’t have matched this criteria right okay so that’s the every method of an array similarly we can look at sum so tell me if at least one element of the array matches a condition so here again console.log start with that let’s create arrow function um so whoops we’ll start off with uh let’s use the fibonacci numbers so sum true or false well let’s start off here with an arrow function number are all the nums greater than 50. true or false true okay are they all greater than 100 are there any of them there’s at least one item greater than 100 that’s what we’re testing for here false there’s no items in that fibonacci sequence that we have here in our array that are greater than 100 all right so hopefully first of all you can see that there are some very useful uh helper methods on the array built in native secondly more examples of arrow functions that are used inside of some of these methods hopefully that’s useful let’s keep going see in the next video thanks you have to try really hard to force javascript’s compiler to throw an exception with the code that you write unless you simply just typed in the code incorrectly now i suppose some might consider the fact that javascript tries so hard to work with whatever crazy code you offer it uh as a positive thing but personally i wish that javascript’s compiler would throw errors more often i mean you should never be able to do something as absurd as what i’m about to do here let me paste in a little code i mean this makes absolutely no sense here we’re going to attempt to multiply seven times undefined divided by panama okay what’s the answer to that well um you know it it looks at and says well i you know i’m not really sure that that’s going to come out to be a number so i’m just going to return not a number and we can check for that not a number and you know i guess we can account for that in our logic of our application but kind of wish it would just throw an exception but i guess that’s not the way that javascript is made to work i suppose it tries to do whatever it can because it i guess figures that perhaps people come from many different programming backgrounds or that since it’s a dynamic language maybe it should be able to accommodate any of these crazy situations but when javascript does encounter finally something that it cannot work with uh we call that an error we call that sometimes an exception an exceptional situation an exception something it just can’t work with and the javascript runtime will simply a quit at that point throw up its hands and say i can’t do anything with this line of code and if i can’t do anything with this line of code that means i can’t do anything with any other lines of code i quit so it’s when it does actually reach an exception it completely bails out on any additional code that you might have written all right so when this happens and you can identify where in code these issues are likely occur you can and should build some safeguards to ensure that they never happen again like in this case we might write several lines of code prior to attempting line number one we might do things like to ensure that if for example these values were contained in variables we might try to make sure the variable was not undefined we would try to make sure that the variable had a data type of number and not string or something else right so that we could do that calculation and expect a real number to to be assigned to the variable a oh if we were working with objects we might want to make sure that the property actually existed on the object that was passed into our function and so we would look and say do you have a do you have a property with this name does it have a value okay we can work with that and so there are some safeguards that you can kind of build around your code to bolster it to make it uh to make it more resilient to the possibility that its inputs were bad and that it ultimately might throw or raise an exception so other times these things might be completely out of your control you still need to write your code in a defensive manner so for example you might want to request data maybe json data from a web server that hosts a web api and depending on what you’re requesting and depending on whether the web server is functioning correctly in that moment you may or may not receive the data that you’re expecting so this might cause your code to throw an exception well here’s another case where you should be able to kind of code defensively account for the possibility that an exception could occur because calling into another resource across the world is a highly risky proposition and it could result in an exception so an exception in an era i use those terms kind of interchangeably in my mind they’re the same thing but whenever a a problem arises an exception is raised by uh by javascript in some way the information about that exception is boxed into one of these um built-in natives that we learned about several videos ago uh that were were created in the exception capital e exception function and it will give you an opportunity to inspect that exception or that error object uh and look at for example the error message and be able to handle it gracefully and we’ll talk about that in this lesson you can safeguard your code the code that you suspect or that you know would be prone to throwing exceptions and you can do that by wrapping it in a construct in javascript called try catch so here let me comment this out and then i’m going to create some examples let’s create one where i know i can create an exception so here i’m going to create a function called before try catch so here we’re just going to create one and not not attempt to catch any issues that might be uh that might be created now here i’m going to just say let this variable obj equal to undefined and i’m going to act like obj is an object so i’m going to just act like it should have a property on it so i’m going to do console.log obj.b alright and i know that this obj does not have a property b that should trigger an exception in javascript it’s one of the few cases where we can actually force it to happen so if that happens correctly as i suppose then you should never be able to execute this line so if the previous line of code grows an exception you’ll never see this all right and just want to point this out here i’m going to have to escape this in my literal string this single quote in the contraction yule because uh javascript and in this case visual studio code doesn’t recognize it as an apostrophe it recognizes it recognizes it as the closing single quote for my literal string so to escape that character and treat it like i need to treat it as an apostrophe i’ll use a backslash right in front of it so now that little combination of characters will treat it as an escaped apostrophe instead of the closing single quote all right but any rate just an aside there line 7 should never get executed because i uh i’m expecting line number six to essentially throw an exception so um here’s what we’ll do we’ll just call before try catch and we’ll execute that and you can see that cannot read property b of undefined perfect all right now let’s let’s introduce a different function called after try catch to kind of show you how this works i’m going to comment out the call to before try catch here let’s just grab all this and copy it all but i’m going to first of all create a try and um i’m going to go ahead and just hit uh enter on my keyboard i’m going to use the arrow keys to like create a try catch statement all right see that and inside of the try i’m going to attempt to perform these three lines of code now i don’t have high hopes for 17 ever ever running however i suspect that what i can do is do something like this if we were to reach an exception in line number 16 which we will so in this case what i can do is say i caught an exception that was thrown by the javascript compiler and i can even inspect that error object and i know that it has a message property so we’ll do something like that but the key here is that this will not break my application my application can continue to execute so i can go console.log my application is still running so even if we encounter an exception like i suspect we will in line number 16 we can catch the exception handle it do something and then move on so let’s start with this then we can move on see there’s other things we can do here whoops what am i doing wrong here oh i need to actually now call my after try catch so now let’s try to run it all right i caught an exception cannot read b property b of undefined but my application is still running so it did not completely just shut down my application perfect now what i can do is actually add another statement called finally and this will run regardless of rather my try makes it successfully all the way through or whether the catch has been invoked uh so i can just do console.log this will happen no matter what all right and usually use a finally statement to clean up any resources that you no longer need i’m not sure how useful that is in javascript personally but you might find a use for it all right and so you can see that we have we have hit the catch but then it also executed the finally statement before continuing on with the remainder of the application so there’s a pretty effective software development strategy of throwing custom exceptions from your functions with the intent that those exceptions are caught by the caller so it’s a form of communication if it succeeds then it should succeed quietly but if it fails your function would then throw an exception that would be handled by the caller and it can decide what to do next so i’m going to comment everything we’ve done so far out and we’re going to create one more example here so let’s do that and i’ll comment all this out too and let’s go here okay so this time let’s go function perform calculation and this calculation will take and look at uh a object that will pass in and we’re going to say hey if that object obj dot has own property b wait if it doesn’t have its own property so i could do equals false like that or i can do a shorthand version of this by just using the exclamation mark right before the expression see that that exclamation mark it kind of makes it the negative so if has own property returns false then the entire expression will be true this is if it if not has own property equal true essentially then what we can do is actually throw a new error all right so here we’ll just describe or give it the message we want to to tell what the problem is object missing property all right otherwise if that turns out to be a truth that the object does have its own property then we can continue with the calculation and uh i might just return you know the value six or something like that okay whatever the the calculation using obj dot property b all right so here we go now we’re going to call into that function perform higher level function operation and here let’s um do let’s be j let um that value equals zero all right um and then um let’s do a try around value equals perform calculation and i’m passing in an object that’s undefined right because i didn’t set it to anything in line 41 so i know it’s going to throw an exception here i’m going to catch it i know it’s going to come back to me as a boxed built-in native error and [Music] print that out and what i can do then is kind of to show how this would work is uh if um you know value is uh equal to zero i know that the perform calculation didn’t work so i can run my contingency perhaps i can do some retry logic you know whatever i need to do to to make my application uh handle this exception gracefully and then continue with whatever logic makes sense after that so let’s see if this works i think i got this right let’s call perform higher level operation and um i’m not sure what to expect to see here but i don’t want to see any exceptions pop up other than the one that i’m printing out and throwing um here so let’s try that all right i think in this case i’m gonna need to do this let’s see if that works all right try that again all right that worked perfectly okay so in this case created an object passed it in doesn’t have property b so we throw an error remember this is a strategy for us to do some checking and then look to make sure that if an exception happens we can handle it if not we grab the value back but if the value is zero then perhaps we need to we we hit an exception maybe there’s some other flag we can use to see whether we’re getting the value we thought perhaps in the catch we can do some work maybe in the final statement it makes more sense to put it there but at any rate we can gracefully recover from the exception being thrown uh because that’s kind of just our strategy that hey this function does not have what it needs so you’re calling into it but you didn’t give us what we needed so you’re gonna have to write some logic to figure out what to do next all right that’s all i’m trying to say there so this is a good start to help you understand that you do have options when you think about how to safeguard your application against potential exceptions that could occur and shut down your code completely ideally you could think of all the ways that your code could possibly fail and attempt to mitigate those potential issues up front but after you’ve done a reasonable amount of work to perform gated checks like i demonstrated here in line number 33 34 and 35 uh then you can ultimately wrap your code in um a try catch statement try catch finally whatever works for you and furthermore you can throw custom errors from one function to another as a means of communicating failure and allowing the caller to implement some contingency like we looked at line number 50 there maybe even some retry logic to ensure that ultimately the application is performing correctly and it can recover from any exceptional situations all right that’s all we really wanted to say all right so we’re doing great almost done we’ll see in the next video thanks up to now i have avoided talking about javascript in the specific context of a web browser i actually re-recorded this entire course from scratch earlier this month because i started talking about javascript uh in a web browser from like the very first video and it became obvious as i that i spent so much time fiddling with the html explaining the dom and ultimately i was struggling to get just to talk about javascript by itself and so that’s why i took a different tact and re-recorded this so this time around as you know i started with pure unadulterated javascript and now here at the very end of this course i’m talking about javascript and how it’s used in a web browser which there are some peculiarities that i wanted to talk about and i hope the approach makes sense i hope that this approach worked for you and even if this isn’t how you wanted to learn javascript i hope you can understand understand and see the the rationale behind it all right enough of the pretense uh as we start dipping our toe into javascript in the web browser i want to talk about the amazing work of a web browser and how it will actually turn a request by just typing in an address and to the point where we’re actually viewing a page on screen i want to talk about how it begins to understand the html that it has downloaded as well as other files like css and javascript files and i want to talk about all the things that it has to consider before ultimately rendering a web page out to the end user to to see it’s it’s really quite amazing so let’s start at the very beginning i don’t want to talk about all the process of of requesting and resolving to an ip address and all that let’s just speak in very broad terms there’s a request made from the web browser to a server and ultimately an html file will be downloaded or or i should say a collection of html is downloaded to the web browser and then there are references to other resources like css files and javascript files and things that begin to be downloaded as well kind of all this happens really at the same time along with everything else i’m going to talk about here um and this isn’t really intended to be deeply technical uh i’m really just going to paraphrase that the general order of events because i’m not really privy to what goes on inside of a web browser i haven’t really looked at the source code but any rate while it’s downloading all the resources it has its html now it’s grabbing its css now it’s grabbing its javascript and it’s working asynchronously in the meantime with what it does have in hand in memory uh as it’s continuing to grab these resources down well while that’s going on the browser is beginning to construct this object-based representation of the html elements in the html page and it constructs them into a series of objects that are called nodes so it’ll create a node for a given paragraph a node for the id of that paragraph a node for the class of that class attribute of that paragraph a node for the text that belongs to that paragraph you can see where i’m going with this everything gets its own little instance of an object and ultimately it’s building this object graph that represents all of these these elements their attributes and their values the text values and so each element node could contain other element nodes as well so a paragraph could conceivably have some div tags or vice probably more likely vice versa a div tag has has a paragraph a div tag has a header has an unordered list which has list items and so on all right so there’s that just that nature of html and the the object model that’s being constructed in memory has to consider all those kinds of relationships as well as the attributes and and the text values of each of those attributes so at any rate the final result of all that work is this rich object model that represents the document that can also be accessed programmatically we’ll talk about that in just a little bit but at some point the browser considers then all the styles that it has downloaded whether embedded in the html page itself or through one or more css files that have been downloaded as well and it also has to consider any of the default styles for uh elements so these are ones that are baked right into the web browser it starts to decide which styles will overwrite the other styles which values will overwrite the other values and so now it has to then start to apply those styles to the various nodes inside of this large object graph of node objects and once it’s kind of settled on which styles to apply to each of the individual nodes it then has to calculate how much space each of those will take up on the web page all right so that it can essentially at some point visually render those onto the web page for the end user to view the next thing that it’s going to do is it’s going to start to parse through the javascript that it’s been downloading from various files and it’ll determine what needs to happen and when it needs to happen so some code can be executed immediately some code is attached to the various events of the various nodes in this object graph of nodes that represent the web document and we’re going to see this in a little bit it’ll impact how we write our code and where we write it in the html document so when we’re talking about this collection of nodes from a programmatic standpoint as well as the entire api of the methods and properties that we can access programmatically to change things about the nodes that represent our document to modify them to add new nodes to remove nodes things of that nature as well as the web browser as a whole and all the functionality that it provides to us like the ability to manipulate uh things like the history the the console window and and any of the other debugging windows that might be available take all of that into consideration and that is that essence something called the document object model or the dom all right and so we’ll talk about the dom uh in the remainder of this video in the next couple of videos but eventually after it’s taken all those things into consideration then it finally will render the page visually to the end user but its work is not done at that point now it’s listening for the user’s interaction with the various nodes inside of the document and when the user interacts it might click or hover or mouse up mouse down it might use a keyboard you know the user can interact with the various elements on the page in various ways and if the software developer or the web developer has attached event handlers functions that should be called in response to those interactions those events then it will the web browser has to say oh yeah we have uh these two functions that we’re going to call because the user clicked on this button go ahead and execute those those two functions now all right so when we create those associations html uh actually gives us a couple of ways to do the create those associations but we’re going to look at some some programmatic only ways to create those associations we’ll talk about that in the next video uh but at any rate uh as developers we can also interact with other apis that are exposed to us for example most web browsers expose the console window so that we can write to that write little error messages out like we’ve been doing up to this point so we’re primarily interested in the document object model as as javascript developers again it contains an object graph that represents every element the attributes of those elements uh the text that might be associated with those elements and the relationship between two elements you know one might contain the other or they might be siblings and so on each of these objects are referred to as nodes as i said earlier and i just want to make the point really quick that when we’re talking about nodes inside of the document object model that shouldn’t be confused with nodejs the environment that we’ve been using up to this point to execute our various little javascript examples they’re completely different they have no relationship to each other all right so at the highest level you have the document node and the document node will contain one or more element nodes and each of those could contain other element nodes but each element node will probably have some attribute nodes associated with it and maybe a text node associated with it okay so the dom also includes a rich api so lots of functions that we can call in order to access the various nodes their attributes uh the text and so on all right so we can find a specific node or a collection of node that match our criteria and then once we have a programmatic handle to a given node or multiple nodes then the api also gives us some functions that we can use to modify the values of those nodes everything from changing the text of a node to changing the attributes of the node like changing the um the class that is associated with that given node we can remove nodes we can add nodes all that programmatically the api also allows us as i mentioned a little bit ago to associate events that are raised by the web browser usually because the end user triggered the event with a mouse over a click whatever the case might be as developers we can associate our functions with those events and then finally the api provides some helper functions to perform various various things one that comes to mind is network operations like being able to call out to another web server to grab data or to grab some other code that can be executed but finally there are several ways that we’re going to talk about in this video to basically write your javascript uh in a web page or associate your javascript with a web page and if you have professional aspirations then you should be aware that not all of these techniques are are smiled upon in fact most of them are frowned upon there’s one that’s that’s not so you might see some examples and here we’ll just add this to our to our uh existing page here that i just created randomly in dom intro.html and i’m going to create a button and in that button i’m going to say click me and then here i’m going to add an on click equal i believe we’ve done this already right but i’m just going to write some javascript right here now using this technique i’m able to pop up box an alert box in the browser to just kind of execute one little simple line of code uh so let me see how i’m going to do this let’s right click on this and let’s rebuild an explorer and from here i can double click and it should open up my default web browser i click click me and i get a message box an alert that pops up with the little message the site says hi okay and i can also do something a little bit different this might be a little bit more akin to what we’ve been doing consoled console.log and i could do hi in the console all right and let’s just refresh that page so i’ll hit refresh i’m going to hit f12 on the keyboard this will allow me to see the console tab and specifically i want to look at the logs when i click the click me button high in the console okay so hopefully that all makes sense now using this technique uh you’re only gonna be able to write one line of code at a time maybe two you might have to write some you know but there’s no doubt that just keep writing a bunch of statements here inside of this on click event right in line in the button is not a great idea so your other decision is or a choice is to actually add a script tag like so now for reasons that i’ll explain a little later typically you don’t see script tags added there you would probably want to put them at the bottom of the document and the reason is pretty simple that the uh that the web browser is going to look at the code line by line and if it encounters a script tag up here and we reference elements in the body those elements may not have been loaded yet into the document object model if we put the script at the very end we can ensure that any everything above this has been loaded already so we can reference the various uh elements in our html all right or the various nodes in our document object model to say in a more programmer friendly way okay so here’s what we can do instead i can actually create a function let’s call this just a click handler and um you know i could even just add message and here i can just do something like console.log um hi and then [Music] maybe dot dot and then maybe a message like that so now in the on click i can kind of wire this up and say hey call click handler and i’ll just say from the button click event all right so we’ll save all that and with any luck you can see where we make the call to the function we’ve created and then passing in a message which will should display in the console log let’s open up our web browser again let’s refresh this page f5 i’m gonna click the click me button and we get hide dot dot dot from the button click event all right so you might be wondering well wait a second you are calling a function before it is defined in your javascript isn’t that a problem no and this is something i wanted to talk about before but never really got a chance to and this applies whenever we’re executing all of our examples in node function declarations are hoisted to the very kind of top of the execution environment so the javascript compiler will go through and look for all the function declarations it’ll put them at the top it knows where they’re at now and then it will continue to execute any additional code so this is in essence added then to the top of the execution chain so when we by the time we get to the click event handler for this button javascript’s already very aware that this function exists all right so small point there but these techniques of using this on click equal and the script tag in this manner these are generally frowned upon professionally you probably want to do what’s called separate your concerns so your javascript may it might be more appropriate to keep it in its own file and to kind of remove all of these references like this like we have there so i’m going to say don’t write javascript in your html page all right and some people might argue with that and say it’s perfectly fine and you know it just depends on how much javascript there is and what your professional aspirations are and the other programmers and what they’re doing in your group but generally speaking what you want to do is kind of just add your code to another file in this case i’m going to create another file i’m going to call this dom intro.js right and then what we’re going to do is actually wire up the event handler to um to the button click event but we’re going to wire it up in our code so what we’re going to do to start off with is to create an iffy so um remember how we to do that we’re going to create a function i’m going to wrap it in a parentheses and then we’re going to say execute immediately all right and in here what we’ll do is we’ll define our function of the click handler and then i’m also going to let’s go here to our dom intro.html i’m going to give this guy an id and i’m going to say your id is my button all right in fact i hope you don’t mind that i’m going to delete all of this out of here all right i’m going to delete all of this out of here it’s gone now and i’m going to go into the dom intro.js and the first thing i need to do is get a reference to my button alright or my button so what we’ll do is let my button equal document dot get element by id and then give it the id i want my button button alright next thing i want to do is go my button add event listener i’m going to say which event i want to listen to in this case i want to listen to the click event and when that happens i want to call click handler and i guess i could pass in a message if i wanted to at this point so um hi from my iffy right now i need to go back to the dom intro.html here i’m going to add a script tag like so script type equals text forward slash javascript source equals and then we’ll give it the name dom intro dot js so save that and now hopefully let’s load this guy up refresh and you can see i did something incorrect let’s go back here let’s get rid of all of this business right there all right now we don’t want to call that method just yet we just want to wire it up to the button and say whenever the click we want to listen for the click event when that happens then we want you to execute click handler all right all right now that we have that in place let’s go ahead and refresh click me and there we go now we get pointer event not exactly what i was looking for if it’s really important to us to pass in the message which i actually forgot about sorry what i’ll do is just kind of wrap this call inside of a function expression so go function like so and inside there we’ll make the call like that and then um hi from iffy all right that should work hopefully so let’s save it let’s try that again there we go that’s the that is what i wanted to happen okay so had a lot to say in this video about the dom and about how to attach your javascript into a web page and still access the various elements of the document object model or this document object by using helper methods like git element i by id passing in the id and now getting a programmatic reference which we can then use to add or even remove event handlers too in this case i’m just adding a function expression to make a call into another function that i created earlier all right hopefully all that makes sense and we can continue on uh in the next lesson and kind of expand on this alright we’ll see you there thanks in this video we’re going to talk about working with the dom specifically how to access dom nodes how to change attributes of those nodes how to add nodes dynamically and more so in the past i’ve created like three or four lines of code and then we would look at look at what those lines did and i wanted to change my tactic for this particular example to show you something a little bit more interesting a little more compelling so i’ve already created a dom nodes html dom node css and dom nodes js and you can see here that i basically created just a little playground it does nothing of practical values completely contrived but it will show you how we can manipulate various down nodes and their attributes uh and you might find some of the the practical side of this how did i accomplish that useful as you pick apart this program and we’ll walk through here in just a moment but again this does nothing useful it has a click me button uh a series of div tags each with a color and the name of the of the color itself and then a number beneath that and i’m just going to click the click me two or three times alright you can see that several things are happening all at once first of all we are changing every time the click me button is clicked we are changing the selected color div you can see the selections change because there’s this thick bottom border applied to that particular div furthermore that color is applied to this number and that number seems to be growing each time we click the click me button so here we’re going to click it we go to pumpkin what happens when we get to the end of our list of colors and i click the click me button one more time we start back over at the beginning of the list and so i can just continue to click this the number is growing i’m using uh relative ms rems in css using it the number of times i’ve clicked it that’s the number of rams that i’m applying to this font and so you can see that things are changing they’re very dynamic and uh i just wanted to kind of it’s a it’s a large enough application to be interesting small enough that i think you can pick it apart and kind of understand what’s going on and that’s really the intent here so let’s take a look at the source code itself and we’ll start with the html there’s really not much interesting here i’m pulling a font from the google fonts and then i’m also applying a style sheet the style sheet itself not a lot interesting in it and i don’t want to take too much time it’s just making everything look a little bit nicer than our previous examples here we’re looking at the result container and that seems to be where we have uh though basically the white area with everything else inside of it this button this row of divs and the number and so you can see that each of these have ids applied to them the click me is my button the color div will contain a series of child divs and i’ll talk about more about that more in just a moment and then the resultive is where we add the current number of clicks that continues to grow and grow here we have our script reference to dom nodes.js that’s where all the magic happens first of all you can see that i’ve created an iffy here and i can roll it up using the little plus and minus right next to that line of code in line one you can see that i’ve created a couple of functions uh one called increment counter one called update ui and then one called handle click you can see that i’ve initialized a variable called counter to the value of zero here i’m getting a reference in line 74 to the button and then i’m wiring it up like we learned about the previous video to every time that the click event is raised for my button i want to add an event listener here we have a function expression that will execute both the increment counter method that we looked at at the very top and then the update ui method that we looked at it was right below it and we’ll go and this is where a lot of the magic happens so we’ll look at that in more detail in just a moment then here you can see in line number 80 i execute update ui in order it as the page loads because again as a immediately invoked function expression i want this to happen as soon as this file is loaded into uh into our html by the web browser okay so uh let’s go here to the top and we can see increment counter is very simple it just takes whatever the current value counter is and increments it by one all right now update ui is where a lot of the magic happens first of all we start off with an array of color objects each color object has a name this is the name that you saw printed kind of in the top middle part of each of the div tags as well as the color value itself and i just grabbed these from a website that has colors i think you see the colors i’ll give you the site in dom nodes.css alright the first thing we want to do is grab the resultive this is where we’re going a reference to that element and we use the id resultive to get an access to it so that we can programmatically work with it this is the div that will contain the current number of clicks not only will we increment the display the the incremented click number but then we will also change its size and its color attributes as well all right next up what we want to do is then set the inner text attribute or property of the result object so this resulted we’re going to set a property called intertext that’s how we’re able to put one two 3 4 inside of that div tag here at the very bottom of our white section of our web page okay and then so you can see this is one way that we are getting a reference to a dom node or a dom element and then changing the attribute we’re changing the text whatever it was we’re overriding it with the current value of counter all right then what we do is additionally access the style of that div so here we’re going to the style object of the result element and then the style object has a series and i can hit the period on the keyboard to look at the intellisense all of these are attributes or properties of the style object for our div tag we can change all of these attributes if we want most of them are visual in nature and here i just want to change the size of the font taking the current value of the counter and appending em to make it larger each time that em being a uh a unit of measure in css all right so that’s how we’re making the changing the number of times that the button has been clicked in in that div tag and then also changing its size every time we click it okay so next up what we want to do is determine what the current color is in our array of colors so here’s what we do we take the current value of counter and we use the modulo or modulus operator which will give us the remainder so if this has been clicked six times and there are six elements inside of our of our um array of colors that we define as a const here at the top then the modulo would be zero there would be zero remainder so we would access the first element of that array and that would be this alizarin it’s that coral color all right and so we would use that so that’s how i’m using and being able to to kind of select each of the items i take the current counter so if it was two and there were six then that would give me a remainder of of what a four so it would be the we would grab the fourth element from our colors array and grab the value property the value property of that particular object and set that as the result style objects color attribute all right moving on now what we want to do is clear out all the existing child color div so i basically tear down and recreate this list of colors by basically removing everything first of all from the previous call to update ui and then i begin to re-implement it if the as i’m looping through each of the color objects to create a new div if it’s the currently selected one then i want to apply not only the bottom border but then also use that color here i guess i already did that part but anyway um this is why i’m setting the inner html to an empty string of the color div because i’m emptying out everything inside of the current div but now i’m going to loop through each of the colors and here i’m basically dynamically creating new div tags so i create a new div tag and then i create a text node with the name of the color for you know whether it’s the first object the second object the third object i’m grabbing that name and creating a text node i append that text node as a child to the div tag that i just created i style it up and then at the very bottom here you can see i actually append that child append that node that i’ve been styling up to the larger outermost color div so i do that six times and if it is the currently selected item then i’m going to change the styling of that particular node by adding a class the selected class and that’s what’s going to add that bottom border in fact here if i wonder if i could just go to here and find selected so there we go it is uh just adding a bottom border of five pixels with no padding all right and so um that’s pretty much it now you’ll see that throughout i’m accessing the style object or attribute of the given div tag setting its width its height and other properties like float padding left padding top and i could have just created a css style and then added it using the same technique that i’ve used here but i chose just to demonstrate that we can get at all those those style attributes in addition to the style object there are other things that we’re able to do to it like append a child to it so we want to we have a a div tag and we want to append something to it we have a div tag and we want to append it as a child to that div tag which is already a child to a div tag child to the body right so hopefully this will help you to see how this whole process works and then we can basically get at any ah any uh dom node we can modify it we can add new child nodes to it um creating them essentially out of thin air and we could even do more like move nodes around if we really wanted to and so on obviously this example didn’t call for that but essentially once we get a handle to an element then we can do anything we want with it that we can conceive of so there are so many options that it didn’t really make sense to kind of go through them in a laundry list basically this is a matter of imagining what it is you want to accomplish getting a reference to the element that you you need to start with determining do i need to create a new element and append it on or do i need to remove elements that are currently child of the existing node which attributes of that know do i want to change and so on until you kind of construct i mean it took me several minutes to to build this example and it started really simply it started by can i just increment the current number of clicks all right i got that working now let’s move on to the next thing can i create a bunch of colors and have them applied to the number can i create a bunch of dibs and apply those colors to the div and so you just keep working at it little by little until you’ve you know tackled essentially the whole the whole application and that’s how i built this all right so um hopefully that was helpful as kind of a larger example that we’re able to to dissect and understand better how to accomplish something that that we conceive of by working with nodes inside of the dom all right so uh let’s continue on i guess we’re pretty much done so let’s wrap it up in the next video see you there thanks i just wanted to briefly congratulate you on finishing this course that’s quite an accomplishment and that’s awesome and i have to say that i definitely respect anybody who puts the time in to learn a new technology or a new skill so you’re awesome i congratulate you and i wish you the absolute best i sincerely hope that this course was helpful to you in some way and that you came away with some confidence in javascript and that you have a solid foundation now to build on and i’d strongly encourage you to keep pushing forward in fact modern development with javascript will require that you learn some of the most popular tools and libraries that are currently in vogue by the javascript software development community as well as the build and deployment process for javascript applications so i i hesitate to recommend specific libraries and frameworks for you to look at because especially on the client because things are changing so rapidly in that space but i think you’d be safe at least if you’re watching this within a couple of years after i record it uh to uh to get started with something like vue.js vue.js or react.js by uh by facebook if you’re going into a corporate uh software development environment like in a big company then you may want to look at angularjs or angular i think the current version as i record this is version five i’m sure they’re going to every six months they’re trying to release a new version of that you’re probably going to learn need to learn a little bit about packages in javascript and using npm or yarn another tool by facebook you probably want to learn a little bit about webpack and parcel but again honestly i kind of feel silly recommending anything because a couple years from now it’s it’s likely that the javascript development community will have moved on past some of these sorts of things so you know at least enough now where you can follow along in those kinds of discussions and begin to stay abreast of of javascript’s frequent and fickle library preferences de jour now on the server side i highly recommend that you learn more about nodejs and if you want to use node to create websites and web apis then you may want to learn another framework called express.js which sits on top of node okay makes it easy for you to build entire websites just on the server side okay so quickly just want to give another plug to my own website here let me type it in for you developeruniversity at devview.com http://www.devu.com i’m learning new things every day and when i do learn them i try to share them on my website so definitely want to come and check it out and check it out every so often finally a quick thanks to microsoft virtual academy you guys are awesome quick thanks to you the viewer for watching this and staying with it through the entire course and i as we close here just want to say that i sincerely and truly wish you the best hope you can leverage this course and do something really awesome and if you do let me know about it so good luck

    By Amjad Izhar
    Contact: amjad.izhar@gmail.com
    https://amjadizhar.blog