Month: March 2025

  • Raymond Murphy English Grammar in Use

    Raymond Murphy English Grammar in Use

    This text is a table of contents and excerpts from the fourth edition of English Grammar in Use, a self-study grammar book. The book covers various grammar points, including phrasal verbs and verb tenses, with numerous exercises and answer keys. Seven appendices offer supplemental information on verb conjugation, spelling, and American English. A study guide and additional exercises are included to aid learning. The excerpts demonstrate the book’s structure and teaching approach, illustrating grammar rules with examples and practice activities. Finally, the book concludes with a detailed index for easy navigation.

    English Grammar Study Guide

    Quiz

    1. Explain the difference between using “will” and “going to” when talking about the future.
    2. Provide an example of a sentence using “would” for a hypothetical situation.
    3. How do you form a question with “shall” and what does it generally indicate?
    4. Describe the difference in meaning between “must” and “have to.”
    5. Give an example of when to use the expression “had better.”
    6. What are two common ways to use the verb + “-ing” form?
    7. Explain how to form the present perfect tense and what it indicates about time.
    8. Give two examples of when “for” and “since” are used with the present perfect.
    9. When do you use “so that” as opposed to “to” when expressing purpose?
    10. Explain how to form a question tag and when the intonation rises or falls.

    Quiz Answer Key

    1. “Will” is often used for spontaneous decisions or offers, while “going to” is used for pre-planned actions or predictions based on evidence.
    2. “If I won the lottery, I would travel the world.”
    3. A question with “shall” is formed using “shall I” or “shall we”, and it is generally used to ask for someone’s opinion or make a suggestion.
    4. “Must” often expresses an obligation from the speaker’s perspective, while “have to” expresses an external obligation, such as a rule.
    5. “You had better finish your homework before dinner” expresses a strong recommendation with possible negative consequences if not followed.
    6. Two common uses of verb + “-ing” are after prepositions (e.g., “I’m good at playing”) and to form continuous tenses (e.g., “I’m reading”).
    7. The present perfect is formed using “have/has” + the past participle, and it indicates a connection between the past and the present.
    8. “I have lived here for five years” uses “for” to specify the duration, while “I haven’t seen him since last summer” uses “since” to specify the starting point.
    9. “So that” is often used when the purpose is negative or involves a result clause; “I hurried so that I wouldn’t be late,” whereas “to” is more common for general purpose; “I went to the store to buy milk.”
    10. Question tags are formed with an auxiliary verb and a pronoun, with the tag reflecting the tense of the main verb; intonation rises when it is a real question, and intonation falls when seeking agreement.

    Essay Questions

    1. Discuss the different uses of modal verbs, providing examples of each, and explain how they add nuance to English sentences.
    2. Analyze the differences between using “-ing” and “to” forms with verbs, including how the meaning can shift based on the choice of form.
    3. Explore the uses of the present perfect and how it differs from the past simple. Include situations where each tense would be more appropriate.
    4. Explain the use of conditional sentences, focusing on the first and second conditional. Explain the differences in hypothetical situations.
    5. Discuss how prepositions impact the meanings of English sentences and include specific preposition examples to explain meaning changes.

    Glossary

    Adverb: A word that modifies a verb, adjective, or another adverb, often indicating manner, place, time, or degree (e.g., quickly, here, yesterday, very).

    Apostrophe: A punctuation mark (‘) used to indicate missing letters in contractions (e.g., can’t, I’m) or possession (e.g., John’s car).

    Auxiliary Verb: A verb that helps another verb (e.g., be, have, do, will, can, may) to form tenses, questions, and negatives. Also called helping verbs.

    Clause: A group of words containing a subject and a verb that forms a part of a sentence.

    Conditional: A sentence that expresses a condition and its result, often starting with “if” or “unless”.

    Conjunction: A word that connects words, phrases, or clauses (e.g., and, but, or, because, when).

    Contraction: A shortened form of a word or phrase, with missing letters replaced by an apostrophe (e.g., isn’t, they’ve).

    Determiner: A word that introduces or specifies a noun (e.g., a, the, my, some, this).

    Gerund: The “-ing” form of a verb when used as a noun (e.g., Swimming is fun).

    Infinitive: The basic form of a verb, usually preceded by “to” (e.g., to be, to go, to eat).

    Modal Verb: An auxiliary verb that expresses possibility, necessity, permission, or obligation (e.g., can, could, will, would, may, might, must, should).

    Noun: A word that represents a person, place, thing, or idea (e.g., friend, London, book, happiness).

    Past Participle: The form of a verb used to form perfect tenses (e.g., spoken, eaten, written) and the passive voice.

    Phrasal Verb: A verb combined with an adverb or preposition to form a new meaning (e.g., look up, give up, get on).

    Possessive: A form showing ownership (e.g., my, your, his, her, its, our, their, John’s).

    Preposition: A word that shows the relationship between a noun or pronoun and another word in a sentence, often indicating direction, time, place, or manner (e.g., in, on, at, to, from, with, by).

    Pronoun: A word that replaces a noun (e.g., I, you, he, she, it, we, they).

    Question Tag: A short question added to the end of a statement (e.g., You’re tired, aren’t you?).

    Relative Pronoun: A pronoun that introduces a relative clause (e.g., who, whom, whose, which, that).

    Short Form: See contraction.

    Subjunctive: A verb form expressing wishes, suggestions, or hypothetical situations (e.g., “I insist that he be on time”).

    Superlative: An adjective or adverb expressing the highest degree of a quality (e.g., best, most difficult).

    Syllable: A unit of pronunciation having one vowel sound, with or without surrounding consonants (e.g., re-mem-ber has three syllables).

    Tense: A verb form that indicates time (e.g., present, past, future).

    English Grammar Essentials

    Okay, here’s a detailed briefing document based on the provided excerpts from “15001-I Raymond Murphy ( PDFDrive ).pdf”, focusing on key themes and concepts related to English grammar:

    Briefing Document: English Grammar Review

    I. Introduction

    This document provides a review of key grammatical concepts extracted from “15001-I Raymond Murphy ( PDFDrive ).pdf,” a resource for English language learners. The focus is on tenses, modals, verb patterns, question formation, and other essential elements of English grammar. This document will be helpful for students of English grammar in identifying key grammatical structures and rules.

    II. Main Themes and Key Concepts

    A. Tenses and Time:

    • Future Tenses: The document introduces various ways to express the future, including:
    • Present Continuous for future arrangements (e.g., “I’m playing volleyball” indicating a future, planned action).
    • “Going to” for intentions and predictions (e.g., “I’m going to clean my room.”).
    • “Will/Shall” for offers, promises, and spontaneous decisions (e.g., “I’ll help you with it.”). It also covers future continuous (“will be doing”) and future perfect (“will have done”).
    • “When I do / When I’ve done”: This section indicates that we use the present simple or present perfect when talking about the future in time clauses using ‘when’ or ‘if’.
    • Present Perfect: Used to describe experiences or actions with a connection to the present, often with “for” and “since” to indicate duration. As stated in the text, “When we talk about a period of time that continues from the past until now, we use the present perfect (have been / have traveled etc.).”
    • The text also explains the use of present perfect to talk about life events or time periods up to the present.
    • Contrasted with past simple, which is for completed actions in the past (e.g. “It was cold last week.” vs “The weather has been cold recently”).
    • There is emphasis on the use of ‘for’ and ‘since’ with the present perfect, and the use of ‘it’s … since’ to describe the time elapsed since something happened.
    • Past Simple: Used to talk about finished actions in the past. (e.g., “My grandfather died before I was born.”) and the use of ‘did’ in negative and interrogative past simple clauses.
    • Present Simple: Used for regular, habitual actions or general truths. (e.g. “He always gets ill”).

    B. Modals:

    • Ability: “Can” and “could” for ability, and “be able to” as an alternative. (e.g. “Are you able to put the fire out?”)
    • Possibility & Permission: “May” and “might” for possibility, and “can,” “could,” and “may” for permission (e.g. “May I come in?” is more formal).
    • Obligation & Necessity: “Must” and “have to” for obligation; “mustn’t” for prohibition; “needn’t” for lack of necessity. (e.g., “You mustn’t touch the paintings.”)
    • Advice & Suggestion: “Should” for advice or suggestion. Also introduces “had better” and “It’s time…”. (e.g. “You should eat something now.”).
    • Requests & Offers: “Can,” “could,” and “would” used to ask people to do things, also “Can I have… ?” and “Could I have…?”. Includes the use of “do you mind if I?” and “is it alright/ok if I…?”
    • Would: Explores different uses of “would,” including conditional sentences, polite requests (“Would you please be quiet?”) and offering something (“Would you like a cup of coffee?”).
    • Modal verbs in general: “can” and other modal verbs – See Appendix 4.

    C. Verb Patterns:

    • Verb + -ing: Discusses verbs followed by the -ing form (gerund), like “enjoy doing,” “stop doing,” and expressions like “be/get used to.” (e.g., “I enjoy swimming.”). It also covers the structure “verb + preposition + -ing”, as in, “succeed in -ing”.
    • Verb + to…: Explores verbs followed by the infinitive with “to,” like “decide to,” “forget to,” and “want you to.” (e.g., “I want you to go”).
    • Verb + -ing or to…: Examines verbs that can be followed by either the gerund or the infinitive with “to,” such as “remember,” “regret,” “try,” “need,” and “help,” often with differences in meaning. (e.g. “Remember to lock the door.” vs. “I remember locking the door.”). Also covers verbs such as ‘like’.
    • Preposition + -ing: Covers the structure of using ‘-ing’ forms after prepositions. (e.g. “I’m good at playing the guitar.”)
    • “-ing” Clauses: Explains how to use ‘-ing’ clauses, such as, “Feeling tired, I went to bed early”.
    • Object + -ing : Addresses the structure of using an object between a verb and an ‘-ing’ form, as in, “I can’t imagine George riding a motorbike”.
    • Passive ‘-ing’ form: Introduces the structure of the passive ‘-ing’ form, ‘being done’, as in, “I don’t mind being kept waiting”.
    • ‘having done’: Introduces the use of ‘having done’ to talk about completed actions, as in, “They admitted having stolen the money”.

    D. Questions and Negatives:

    • Question Formation: Covers the use of “do/does” in present simple questions, and “did” in past simple questions. The document also discusses the use of auxiliary verbs, such as modals, in questions. The use of ‘why’ in negative questions is also highlighted: “Why don’t we eat out tonight?”. It also covers embedded questions, where the usual question word order is not followed. (e.g. “Do you know what he is doing?”)
    • Negative Sentences: The use of ‘did not’/’didn’t’ is highlighted for past simple negative sentences, and the use of auxiliary verbs in negative structures is shown.
    • Answering Negative Questions: The document outlines how to answer negative questions in English, explaining the difference between ‘yes’ and ‘no’ in this context. (e.g. “Don’t you want to go?” “Yes, I want to go.” or “No, I don’t want to go.”)
    • Question Tags: Explains question tags and how they are used to invite agreement (“It’s a nice day, isn’t it?”) or to ask real questions (“You haven’t seen Lisa today, have you?”). The change in intonation and usage is also discussed. The document also outlines which question tag follows ‘Let’s’ and ‘Don’t’.
    • Negative Questions with positive tags: The document introduces the usage of “negative sentence + positive tag” to ask for things, information or to ask people to do things. (e.g. “You haven’t got a pen, have you?”)
    • Asking questions in passive voice: The structure of using question words in questions that are in passive voice is addressed (e.g. “When was this house built?”).

    E. Other Key Grammatical Points:

    • ‘S and Of: The document highlights the use of ‘s and of to show possession. It also covers the use of ‘s with time words and periods of time.
    • Pronouns: Covers the use of possessive pronouns, such as ‘a friend of mine’
    • Irregular Verbs: Points to an Appendix for a list of irregular verb forms.
    • Short Forms: An overview of the common short forms used, such as ‘m and ‘ve, and when to use them is provided. This includes using ‘s for is/has, and ‘d for would/had. It also addresses when to use short forms after question words.
    • Spelling Rules: Covers common spelling rules such as adding ‘s’ to nouns, changing ‘y’ to ‘ies’, or ‘i’ before adding ‘ed’, ‘er’ or ‘est’, also the rules for doubling the final consonant in words.
    • Numbers: It touches on how we see a quantity of time, distance or money as one thing in English, and therefore use a singular verb with it. (e.g. “Three years is a long time”).
    • Verb + preposition combinations: It discusses different verb and preposition combinations that commonly appear in English, and which prepositions follow specific verbs.
    • Adjective + preposition combinations: It discusses different adjective and preposition combinations that commonly appear in English, and which prepositions follow specific adjectives.

    III. Quotes and Examples

    The briefing document integrates direct quotes from the source to emphasize concepts:

    • “When we taLk about a period of time that continues from the past until now, we use the present perfect (have been / have travelled etc.).”
    • “That bag looks heavy. I’ll help you with it. (not I help)”
    • “Could you wait a moment, please?”
    • “‘Do you mind if I use your phone?’ ‘Sure. Go ahead.’”
    • “It ^ supposed to be a secret.”
    • “Many people don’t have enough to eat. (not Many people doesn’t)”
    • “I’m going to a wedding on Saturday. A friend of mine is getting married. (not a friend of me)”
    • “If we go by bus, it will be cheaper.”
    • “They admitted having stolen the money.”
    • “I hurried so that I wouldn’t be late.”

    IV. Conclusion

    This briefing document outlines crucial aspects of English grammar based on the provided source. It highlights tenses, modals, verb patterns, question formation, and other areas, all of which are crucial to mastering English grammar. The use of examples from the text provides a practical understanding of grammatical concepts. This document should be a valuable reference for those studying or reviewing English grammar.

    English Grammar Guide

    What is the difference between ‘going to’ and ‘will’ when talking about the future?

    ‘Going to’ is generally used for future plans and intentions, especially when there is evidence that the plan has already been decided, whereas ‘will’ is often used for spontaneous decisions, offers, promises, and predictions. For example, you would use “I’m going to clean my room” if it is a planned activity, but “I’ll help you with that” is a spontaneous offer to assist. ‘Will’ can also be used for predictions without necessarily implying prior planning, like “It will rain tomorrow”.

    How do I know when to use the present perfect (have/has + past participle)?

    The present perfect is used to talk about a period of time that continues from the past up to the present. It connects the past to the present. For example, “I have traveled a lot” refers to your experiences in life up to this point. It is also used to talk about actions that are relevant to the present. The present perfect uses “for” and “since” to indicate the duration or starting point of something that began in the past and continues to the present, like in “She’s lived in Berlin for the last few years.”

    What is the difference between using ‘for’ and ‘since’ with the present perfect?

    Both ‘for’ and ‘since’ are used with the present perfect to express how long something has been happening. ‘For’ is used to express a duration of time (e.g., “for five years”), while ‘since’ is used to express a specific starting point in time (e.g., “since 2010”). For example, you might say, “I have lived here for ten years,” or, “I have lived here since 2013.”

    When do I use ‘can,’ ‘could,’ and ‘may’ for requests and permission?

    ‘Can’ and ‘could’ are both used to ask for things or permission, with ‘could’ being slightly more polite. ‘Can’ is common in informal requests or when asking to do something. ‘May’ is more formal and is often used for seeking permission. For example, you might ask, “Can I have the salt?” “Could I borrow your phone?” or “May I come in?”. “Do you think you could…” is also a common way to make a more polite request.

    What is the structure for conditional sentences using ‘if’?

    There are different conditional structures using “if”. One structure involves “if + present simple, will + infinitive,” which talks about real or possible future situations (e.g., “If we go by bus, it will be cheaper”). Another structure is “if + past simple, would + infinitive,” for hypothetical situations (e.g., “If I knew, I would help”). There’s also “if + past perfect, would have + past participle,” which deals with unreal past conditions and their consequences (e.g., “If I had known, I would have helped”). These are often used to express possibilities or impossibilities in the present or future.

    How do I correctly use question tags at the end of sentences?

    Question tags are mini-questions added to the end of a statement. They are used to seek agreement or confirmation and consist of an auxiliary verb and a pronoun. If the main clause is positive, the tag is usually negative, and vice versa. For example, “It’s a nice day, isn’t it?” If your voice goes down at the end of the tag, you are inviting agreement. If it goes up, you are genuinely asking a question. After “Let’s,” the question tag is “shall we?” After “Don’t,” it is “will you?” The meaning of a question tag changes with the intonation.

    What are the rules for forming the possessive with nouns (like ‘s) and where should I use ‘of’?

    Singular nouns use an apostrophe + s (‘s) to show possession (e.g., “my sister’s room”). Plural nouns that end in ‘s’ use an apostrophe after the ‘s’ (e.g., “my sisters’ room”), whereas plural nouns not ending in ‘s’ use apostrophe + s (e.g., “the men’s changing room”). For things, ideas, and locations, we generally use “of” to express possessive relationships (e.g., “the temperature of the water”). However, ‘s can be used with places, time words, or periods of time (e.g. “Italy’s prime minister”, “yesterday’s newspaper”, “a week’s holiday”).

    How do I choose between using ‘like’ and ‘as’ as prepositions?

    ‘Like’ is used as a preposition to show similarity, for example, “He is like his father.” ‘As’ is often used in expressions describing someone’s job, function, or role, for example, “She worked as a tour guide,” or for when the two things are happening at the same time, “I was thinking as I walked”. ‘As’ can also indicate the manner or way something is done. In addition, ‘as if’ is used to describe something that looks like something else, such as “She acts as if she owns the place”.

    English Grammar in Use

    Okay, here is a detailed timeline and cast of characters based on the provided text:

    Timeline of Events and Topics

    This source is not a narrative, so there is no single timeline to follow. Instead, this timeline represents topics covered in the book:

    • Basic Verb TensesIntroduction to Present Simple (I do) and Present Continuous (I am doing) for future events.
    • Introduction to future tenses using (I am) going to (do)
    • Introduction to future tenses using Will / shall
    • Differentiating between “Will” and “Going to”.
    • Introduction to future continuous (will be doing) and future perfect (will have done).
    • Use of “When I do” / “When I’ve done”
    • Use of when and if for future actions.
    • Modals:Exploring the usage of Can, Could, and (be) able to.
    • Using Could (do) and Could have (done).
    • Distinguishing between Must and Can’t.
    • Using May and Might (Part 1 & 2)
    • Differentiating between Have to and Must.
    • Using Must, Mustn’t, and Needn’t.
    • Exploring Should (Part 1 & 2).
    • Using Had better and It’s time…
    • Understanding Would.
    • Using Can/Could/Would you… for requests, offers, permission, and invitations.
    • -ing and to…Using verb + -ing (enjoy doing, stop doing etc.).
    • Using verb + to… (decide to, forget to etc.).
    • Using verb (+object) + to… (I want you to…)
    • Exploring verb + -ing or to… (remember/regret etc.)
    • Exploring verb + -ing or to… (try/need/help)
    • Exploring verb + -ing or to… (like/would like etc.)
    • Using Prefer and would rather.
    • Understanding preposition + -ing.
    • Using Be/get used to something.
    • Using verb + preposition + -ing.
    • Using expressions with -ing.
    • Understanding To, for… and so that…
    • Using adjective + to…
    • Differentiating To…(afraid to do) and preposition + -ing (afraid of -ing).
    • Understanding See somebody do and see somebody doing.
    • Using -ing clauses.
    • Present Perfect:Present Perfect (I have done) as a time frame from the past until now.
    • Using “for” and “since” to express the duration of an action.
    • Differentiating between present perfect and simple past.
    • Using the present perfect for recency or a lack of a time marker.
    • Forming present perfect and past simple questions.
    • Past SimpleUsing did/didn’t in questions and negative sentences
    • Using have (not have got) for actions and experiences
    • Auxiliary Verbs and QuestionsUnderstanding auxiliary verbs in questions.
    • Using short form answers.
    • Using question tags.
    • Understanding question order.
    • Future Tense“Going to” for planned actions.
    • Use of “Will” for offers, agreements, promises and requests.
    • Using Shall I…? / Shall we…? for suggestions.
    • Dialogue practice with future plans.
    • Requests, Offers, and InvitationsUsing can and could for making requests.
    • Using “Can I have …?” / “Could I have …?” for requesting items.
    • Using Can, Could, and May to ask permission.
    • Using Would you like…? to offer or invite.
    • If ClausesConditional sentences type 1 and 2
    • Distinction between using “if we go” and “if we went.”
    • Use of supposed to be.
    • Other Grammar ConceptsUse of “neither do I” or “Nor do I”
    • Use of “I think so” / “I hope so”
    • Using question tags.
    • Direct and indirect questions.
    • -ing form after some verbs.
    • Passive Voice
    • Use of “for” and “to” for purpose.
    • Use of “so that.”
    • Singular and plural nouns and verbs
    • Possessives using ‘s.
    • Use of own.
    • Using there is and it is.
    • Using “each” and “every.”
    • Definition and usage of various nouns.
    • Use of adjectives and prepositions.
    • Understanding phrasal verbs.
    • Short forms (contractions).
    • Spelling Rules.
    • Adverbs and prepositions
    • Understanding comparatives and superlatives
    • Using conjunctions
    • Continuous Verb forms
    • Determiners
    • Modal verbs
    • Negative sentences
    • Regular and Irregular verbs
    • Relative clauses
    • Subjunctive verbs
    • Syllables
    • Various verb tenses
    • Adjectives and adverbs.
    • Apostrophes.
    • Using many, much, few, and little.
    • Using like and as.
    • Understanding the difference between during and for
    • Understanding by, of, to, and for prepositions.
    • Using “some,” “any,” and “no.”
    • Understanding “the,” “a,” and “an.”
    • Using since and for
    • Understanding “if,” “when,” “unless.”
    • Using question tags.

    Cast of Characters

    • Dave: One of the participants in a sample conversation discussing Jane’s travels. He initiates the questions about Jane’s past experiences.
    • Jane: Another participant in the sample conversation. She provides details about her past travels, specifically to China and India.
    • Adrian: Mentioned in a sample sentence as someone who is never ill.
    • Sue: Mentioned in a sample sentence as someone who lives in Berlin.
    • Tom: A person who attempts to schedule a visit with the reader, but the reader is unable to accept due to prior engagements.
    • Joe:Engages in a sample dialogue with Sarah, talking about a business trip to London and her personal life.
    • He tells Sarah that Matt is in Canada
    • In the dialogue, he discusses that he has been unemployed for months and is going to Canada.
    • Sarah:Engages in a sample dialogue with Joe, asking about his life and mentioning her friend’s delayed train.
    • She asks him about Matt’s whereabouts
    • She inquires about his job situation
    • Matt: A person who is mentioned by Joe to be in Canada.
    • Jenny: In a sample conversation, she’s making plans to go to the cinema with Helen.
    • Helen: Participates in two dialogues:
    • She is making cinema plans with Jenny.
    • She then invites Tina to the cinema
    • Tina: She’s invited to join Jenny and Helen at the cinema.
    • Louise: In a sample conversation, she is waiting in a restaurant with Sarah for Paul.
    • Paul: Is late for dinner with Louise and Sarah
    • Emily: Mentioned in a sample sentence as someone who earned a lot of money this year, but not so much last year.
    • Mr. Carter: Mentioned as a family with a house.
    • Jack and Karen mentioned as a couple getting married.
    • Shakespeare: Mentioned as a person who has written a play
    • Various Unnamed Friends: These characters appear in various example sentences and dialogs within the textbook, providing contexts for grammatical practices.

    Note: Most characters do not develop beyond their brief appearances in example sentences or dialogues. They are primarily used to illustrate grammar points.

    If you have any more sources or need further clarification, just let me know!

    A Guide to English Phrasal Verbs

    Phrasal verbs are combinations of a verb and another word, which can be a preposition or an adverb [1, 2]. The second word often gives a special meaning to the verb [3].

    Here are some general points about phrasal verbs:

    • They often consist of a verb and one of the following words: in, out, on, off, up, down, away, back, by, about, through, along, over, forward, or around [1].
    • Phrasal verbs are often used with verbs of movement [1].
    • The second word can change the verb’s meaning [3]. For example, “break down” means that the engine stopped working [3].
    • Sometimes a phrasal verb is followed by a preposition. For example, “run away from” [4].

    The sources provide many examples of phrasal verbs, grouped by the second word:

    Phrasal verbs with “in” and “out” [5]

    • Examples include: “get in,” “move in,” “drop out,” “leave out,” “join in,” “eat out,” “take in,” “drop in,” “get out of.”
    • “Get in” can mean to enter a car, “move in” can mean to start living in a new place [5].

    Phrasal verbs with “out” [6]

    • Examples include: “find out,” “sort out,” “put out,” “go out,” “carry out.”
    • “Find out” means to discover something, while “go out” can mean leaving a place [6].

    Phrasal verbs with “on” and “off” [7, 8]

    • These are often used for lights and machines. For example, “turn on” or “switch off” [7].
    • They can also be used for events, such as “call off” or “put on” [7, 8].
    • Other examples include “carry on,” “get on,” and “go off” [8].

    Phrasal verbs with “up” and “down” [9-11]

    • “Put up” can mean to place something on a wall [9].
    • Other examples include: “take up,” “turn up,” “use up,” “bring up,” “come up with,” “do up,” “look up,” “put up with,” and “hold up” [10, 11].
    • “Turn up” and “show up” means to arrive [10].

    Phrasal verbs with “away” and “back” [12]

    • Examples include: “go away,” “drive away,” “fly away,” “take away,” “walk away,” and “run away” [12].
    • “Give away” means to give something for free, while “take something back” means to return it [12].

    Object placement with phrasal verbs:

    • If a phrasal verb has an object, the object can usually be placed after the phrasal verb or between the verb and the particle. For example, you can say “turn on the light” or “turn the light on” [4].
    • However, if the object is a pronoun, it can only be placed between the verb and the particle. For example, “turn it on” [4].

    The sources also provide exercises to test your knowledge of phrasal verbs [13].

    English Verb Tenses: A Comprehensive Guide

    The sources provide a comprehensive overview of verb tenses in English, including their forms and uses. Here’s a discussion of verb tenses based on the provided material:

    Present Tenses

    • Present Simple This tense is used for general truths, repeated actions, and habits [1, 2]. The structure of the present simple is the base form of the verb, with an -s added for third-person singular subjects (he/she/it) [3]. For example, “Water boils at 100 degrees Celsius” and “I always get hungry in the afternoon” [2].
    • It is also used with verbs of perception (see, hear, smell, taste) [4].
    • It is not usually used in the continuous form when it means ‘believe’ or ‘have an opinion’ [5].
    • Present Continuous The present continuous tense describes actions happening at or around the time of speaking [1, 2]. It is formed using “am,” “is,” or “are” + the present participle (-ing form of the verb) [6]. For example, “The water is boiling,” and “What are you doing?” [2].
    • It can also be used to describe things that are changing [7].
    • Some verbs are not normally used in the present continuous, like “want,” “know,” and “believe” [5].
    • It can be used when “think” means ‘consider’ [4].
    • It is used to describe personal arrangements [8].

    Past Tenses

    • Past Simple The past simple tense is used for completed actions in the past [1, 6]. Regular verbs form the past simple by adding “-ed,” while irregular verbs have different forms [9-12]. For example, “I got home late last night” [13]. It is also used to ask “When…?” or “What time…?” [13].
    • Past Continuous The past continuous describes actions that were in progress at a specific time in the past [6]. It is formed using “was” or “were” + the present participle (-ing form of the verb) [6]. For example, “Katherine was waiting for me when I arrived” [14].

    Present Perfect Tenses

    • Present Perfect Simple The present perfect simple tense connects the past with the present and is used when the exact time of an action is not important [15]. It is formed using “have” or “has” + the past participle [6, 16]. For example, “I have been to China twice” [15].
    • It is used for a period of time that continues from the past until now [15].
    • It can be used with “just,” “already,” and “yet” [17].
    • Present Perfect Continuous This tense focuses on the duration of an action that started in the past and is still continuing or has recently finished [1, 18, 19]. It is formed using “have” or “has” + “been” + the present participle (-ing form of the verb) [6]. For example, “It’s been raining for two hours” [20].
    • The continuous form emphasizes the duration of the action [19].

    Past Perfect Tenses

    • Past Perfect Simple The past perfect tense is used to describe an action that happened before another action in the past [6, 21]. It is formed using “had” + the past participle [6]. For example, “He said he had to go” [22].
    • Past Perfect Continuous The past perfect continuous describes an action that was ongoing before another action in the past [6, 17]. It is formed using “had” + “been” + the present participle (-ing form of the verb) [6].

    Future Tenses

    • Present Tenses for the Future Both present continuous and present simple tenses can be used to describe future events [8, 19].
    • Present continuous is used for personal arrangements [8].
    • Present simple is used for scheduled events [8].
    • “Going to” The structure “going to + verb” is used to talk about future plans and intentions [23, 24].
    • “Will/Shall” “Will” is used to talk about future happenings or situations and for decisions made at the time of speaking [25-28]. “Shall” can be used in questions offering or suggesting something [25, 29].
    • Future Continuous (will be + -ing) is used for actions in progress at a specific time in the future [30, 31]. For example, “We’ll be having dinner then” [32].
    • Future Perfect (will have + past participle) is used for actions that will be completed before a specific time in the future [30, 31]. For example, “we will have finished dinner by then” [32].

    Other Points

    • The present perfect is not used to talk about a finished time in the past [13, 26].
    • American English often prefers the past simple over the present perfect in some contexts [33, 34].
    • The sources provide exercises to test your knowledge of verb tenses [35].

    This information should give you a strong understanding of verb tenses as they are presented in the sources.

    English Grammar Rules

    The sources provide a wide array of English grammar rules, which can be categorized as follows:

    Nouns and Articles

    • Countable and Uncountable Nouns: Many nouns can be used as countable or uncountable, often with a difference in meaning [1, 2]. For example, “a noise” vs “noise” in general [1]. Countable nouns can be singular or plural [3].
    • Articles: Before singular countable nouns, “a” or “an” is used [3]. The article “the” is used in specific contexts [4].
    • Singular and Plural: Plural nouns are used for items with two parts (e.g. trousers, glasses) and take a plural verb [5].
    • Noun + Noun: Compound nouns are created by combining nouns (e.g., “a tennis ball”) [6].
    • Possessives: The possessive “‘s” is used to show possession (e.g., “your sister’s name”) [7].

    Pronouns and Determiners

    • Reflexive Pronouns: Words like “myself,” “yourself,” and “themselves” are used when the subject and object of a verb are the same [8].
    • “Own”: “On my own” and “by myself” both mean “alone” [8].
    • “There” and “it”: “There” and “it” are used in sentences to introduce subjects or situations [6, 9].
    • “Some” and “any”: “Some” and “any” are used with plural countable nouns in different contexts [10]. “Some” can mean a number of, a few of, or a pair of [10]. “Any” is used in questions and negative statements [6, 11].
    • “No,” “none,” and “any”: These words are used to express negation, with “none of” often followed by a plural verb [12].
    • “Much,” “many,” “little,” and “few”: These determiners are used with uncountable and countable nouns to express quantity [6, 13].
    • “All,” “most,” “no,” and “none”: These determiners are used to specify the quantity or extent of something [6].
    • “Each,” “every,” and “whole”: These words are used to describe individual items in a group [6, 14, 15].
    • “Both,” “neither,” and “either”: These words are used to describe pairs of items [6, 16].

    Adjectives and Adverbs

    • Adjectives: Adjectives describe nouns, and can end in “-ing” or “-ed” (e.g., “boring/bored”) [17, 18]. The order of adjectives in a sentence follows a specific pattern [17, 19].
    • Adverbs: Adverbs modify verbs, adjectives, or other adverbs, and many end in “-ly” [17, 20, 21].
    • Comparatives and Superlatives: Comparatives compare two items (e.g., “cheaper”), while superlatives identify the highest degree of something (e.g., “the longest”) [22-24].
    • “So” and “such”: These words are used to intensify adjectives or adverbs [22, 25].
    • “Enough” and “too”: “Enough” means sufficient, and “too” indicates excess [22, 26].
    • “Quite,” “pretty,” “rather,” and “fairly”: These words are used to modify adjectives and adverbs with varying degrees of intensity [22, 27].

    Verbs and Tenses

    • Present Simple: This tense is used for general truths, habits, and repeated actions [28-31].
    • Present Continuous: Used for actions happening now, or for temporary or changing situations [28-31].
    • Past Simple: Used for completed actions in the past [28, 32].
    • Past Continuous: Used to describe actions in progress in the past [22, 28, 33].
    • Present Perfect: Connects the past with the present [28, 32].
    • Future Tenses: “Going to” is used for plans, while “will” is used for predictions or decisions made at the time of speaking [28, 33-36]. “Shall” is used for suggestions or offers [7, 29, 34, 37-39]. Future continuous and future perfect describe actions that will happen at a specific time or before another future action [28, 34].

    Modals

    • “Can,” “could,” and “be able to”: Used for expressing ability or possibility [28, 40, 41].
    • “Must,” “can’t,” and “have to”: Used for expressing obligation or certainty [28, 42-44].
    • “May” and “might”: Used to express possibility or permission [28, 37, 45].
    • “Should,” “ought to,” and “had better”: Used for giving advice or expressing obligation [1, 28, 35, 46-48].
    • “Would”: Used for polite requests and conditional sentences [2, 28, 38].

    If and Wish Clauses

    • “If” clauses: Used for conditional sentences [3, 4, 10, 29].
    • “Wish” clauses: Used to express regrets or desires [4, 10, 29, 49].

    Passive Voice

    • Passive voice: Used when the focus is on the action rather than the doer [5, 29, 50]. “Be” is used in passive constructions [29, 50]. “Have something done” is used to express actions performed by someone else [29, 51].

    Reported Speech

    • Reported speech: Used to convey what someone said, often involving tense changes [29, 52, 53].

    Questions and Auxiliary Verbs

    • Question Formation: Questions are formed using auxiliary verbs, and question words like “who,” “what,” and “where” [29, 54, 55].
    • Auxiliary Verbs: Auxiliary verbs such as “have,” “do,” and “can” are used in questions and short answers [29, 56].
    • Question tags: Used to confirm information or seek agreement [29, 57].

    -ing and to…

    • Verbs followed by -ing: Certain verbs are typically followed by the “-ing” form (e.g., “enjoy doing”) [58-62].
    • Verbs followed by “to”: Other verbs are followed by “to” + the infinitive form (e.g., “decide to do”) [58, 60, 63-68].
    • Verbs with both -ing and to: Some verbs can be followed by either form with little or no difference in meaning (e.g., “begin to do” or “begin doing”) [58, 60, 61].

    Relative Clauses

    • Relative clauses: Used to give more information about a noun, using relative pronouns like “who,” “that,” “which,” and “whose” [17, 69-73].
    • Extra Information clauses: These clauses add additional non-essential information [17, 72, 73].
    • -ing and -ed clauses: Used to shorten relative clauses [17, 74].

    Conjunctions and Prepositions

    • Conjunctions: Words like “although,” “though,” “even though,” “in spite of,” and “despite” are used to join clauses with contrasting ideas [22, 75]. “In case,” “unless,” and “as long as” are used for conditional statements [22, 76, 77].
    • Prepositions: Words like “at,” “on,” and “in” are used to indicate time or position [78-80]. They are also used to express relationships between nouns, verbs, and adjectives [78, 81-88].

    Phrasal Verbs

    • Phrasal verbs: Combinations of a verb and a particle (e.g., “look up,” “take off”) often create new meanings [78, 89, 90]. The position of an object with phrasal verbs can vary [78, 89].

    Word Order

    • Word order: The basic word order in English is subject-verb-object [22, 91]. Adverbs can be placed in different positions in a sentence [22, 92].

    Other Points

    • American English: There are some differences in grammar and spelling between British and American English [93-96].
    • Spelling: There are specific spelling rules for verb endings such as “-s,” “-ing,” and “-ed” [67, 68, 93, 97-101].

    This overview should provide you with a good understanding of English grammar rules as presented in the sources.

    A Comprehensive Guide to English Grammar and Usage

    The sources offer various insights into English usage, covering aspects of grammar, vocabulary, and style. Here’s a breakdown of key points related to English usage based on the provided material:

    Verb Tenses and Usage

    • Present Simple: The present simple is used for general truths, repeated actions, and habits [1]. For instance, “Water boils at 100 degrees Celsius” is a general truth [2]. It is also used with verbs of perception like “see,” “hear,” “smell,” and “taste” [3]. The present simple is not typically used in the continuous form when it expresses belief or opinion [3].
    • Present Continuous: This tense is used to describe actions happening at or around the time of speaking, such as “The water is boiling” [2]. It can also describe changing situations or personal arrangements [3, 4]. However, some verbs, such as “want,” “know,” and “believe” are not typically used in the present continuous [3].
    • Past Simple: The past simple is for completed actions in the past, like “I got home late last night”. It is used to ask about a past time or when something happened [5].
    • Past Continuous: This tense describes actions in progress at a specific time in the past [6].
    • Present Perfect Simple: This tense is used to connect the past with the present when the exact time isn’t important [6]. For instance, “I have been to China twice”. It is used when a period of time continues from the past until now [6].
    • Present Perfect Continuous: This tense emphasizes the duration of an action that started in the past and continues to the present [6]. For example, “It’s been raining for two hours” [5].
    • Future Tenses: The sources cover the use of present tenses for future events (present continuous for personal arrangements and present simple for scheduled events) as well as “going to” (for plans) and “will” (for predictions and decisions) [4, 7, 8].

    Modal Verb Usage

    • Can, Could, and Be Able To: These are used to express ability or possibility [9, 10]. “Could” is also used for polite requests [9].
    • Must and Have To: These express obligation or necessity [11].
    • May and Might: These are used to express possibility or permission [8]. For example, “It might rain later” [8].
    • Should, Ought to, and Had Better: These are used for advice or obligation, with “had better” typically used for specific situations [12-14].
    • Would: This is used for polite requests, conditional sentences, and describing hypothetical situations [15-17].

    Conditional and Wish Clauses

    • If Clauses: These are used to express conditional statements [18, 19]. For example, “If I won a lot of money, I might buy a house” [15].
    • Wish Clauses: These are used to express regrets or desires [19-21]. For example, “I wish I knew…” [19].

    Passive Voice

    • The passive voice is used when the focus is on the action rather than the doer [22]. For instance, “The programme was watched by millions of people” [23]. The sources explain how to form passive constructions using “be” and past participles [22, 24, 25].

    Reported Speech

    • Reported speech is used to convey what someone said, often involving tense changes [26, 27]. For example, changing “I’m not feeling good” to “He said he wasn’t feeling good” [26].

    Question Formation

    • Questions are typically formed using auxiliary verbs and question words such as “who,” “what,” “where,” “why” [28, 29].

    -ing and to…

    • Some verbs are followed by the “-ing” form (e.g., “enjoy doing”) and others by “to + infinitive” (e.g., “decide to do”) [30, 31]. Some verbs can be followed by either with little change in meaning (e.g., “begin to do” or “begin doing”) [32-34].

    Articles and Nouns

    • The articles “a,” “an,” and “the” are used before nouns, with “a/an” used before singular countable nouns and “the” used in specific contexts [35-42].
    • Countable and uncountable nouns have different usage rules.
    • For example, “noise” is uncountable, and “a noise” is countable. [21]
    • “Hair” is typically uncountable but becomes countable to refer to one or more strands of hair, as in “a hair” [21]
    • “Experience” is both countable and uncountable. As an uncountable noun it means knowledge or skill, as a countable noun it refers to something that you have done [22].
    • Some nouns are plural, including “police”, “trousers”, and “glasses” [28].

    Prepositions and Conjunctions

    • The sources address the use of prepositions to indicate time, location, and relationships between words, for example, “at,” “on,” and “in” [43-53].
    • Conjunctions such as “although,” “though,” “even though,” “in spite of,” “despite,” “in case,” “unless,” and “as long as” are used to join clauses and express relationships between ideas [54-56].

    Phrasal Verbs

    • Phrasal verbs, combining a verb and a particle (e.g., “look up,” “take off”) often create new meanings [57].

    Word Order

    • The typical word order in English is subject-verb-object [58, 59].

    Other Important Usage Points

    • American English: The sources note some differences in grammar and spelling between British and American English [60-65].
    • Formal vs. Informal: The sources discuss the use of short forms (contractions) in informal speech and writing [40].
    • “Like” and “As”: The sources discuss the usage of “like” and “as,” explaining that “like” is used to compare things and “as” can mean ‘in the same way’, ‘while’, or ‘because’ [66, 67].
    • “Used to”: The sources explain that “used to do” refers to a past habit, and “be/get used to” describes being accustomed to something [17].
    • “So” and “Such”: These words are used for emphasis. For example: “The food was so hot that we couldn’t eat it.” and “It was such a long day that we decided to go to bed early” [32, 68].
    • “Had better”: This is similar to “should” but is used for specific situations [14].

    This discussion covers the key aspects of English usage explained within the sources.

    The Passive Voice in English

    The sources provide detailed explanations of the passive voice in English, including its formation and usage [1-3].

    Formation of the Passive Voice

    • The passive voice is formed using the verb “to be” in the appropriate tense, plus the past participle of the main verb [4, 5].
    • Present simple passive: am/is/are + past participle (e.g., is cleaned, are seen) [4].
    • Past simple passive: was/were + past participle (e.g., was cleaned, were seen) [6].
    • Future simple passive: will be + past participle (e.g., will be cleaned) [7].
    • Present perfect passive: has/have been + past participle (e.g., has been cleaned, have been seen) [8].
    • Past perfect passive: had been + past participle (e.g., had been cleaned) [8].
    • Present continuous passive: am/is/are being + past participle (e.g., is being cleaned, are being followed) [9].
    • Past continuous passive: was/were being + past participle (e.g., was being cleaned, were being followed) [9].
    • The sources also note that “get” can be used instead of “be” in the passive, primarily in informal spoken English, but only when things happen [10]. For example, “nobody got hurt” [10].
    • The passive infinitive is formed with to be + past participle (e.g., to be cleaned) [7].
    • The passive of doing/seeing etc. is being done/being seen [11].

    Use of the Passive Voice

    • The passive voice is used when the focus is on the action or the receiver of the action rather than the doer [5, 12].
    • It is often used when the doer is unknown or unimportant [12]. For example, “A lot of money was stolen in the robbery” [12].
    • The passive voice is also used when it is obvious who is responsible for the action, or when we don’t want to say who did the action [12].
    • The word “by” is used to indicate who or what performs the action when this is important or needs to be mentioned [4]. For example, “This house was built by my grandfather” [4].

    Active vs. Passive

    • In an active sentence, the subject performs the action, whereas, in a passive sentence, the subject receives the action [5, 12, 13]. For example:
    • Active: “Somebody built this house in 1961.” [12]
    • Passive: “This house was built in 1961.” [13]
    • When using an active verb, the sources say “we say what the subject does,” and when using a passive verb, “we say what happens to the subject” [12].

    Passive with Two Objects

    • Some verbs can have two objects [14]. This means that there are two ways to form a passive sentence, often beginning with the person receiving the action [14]. For example, with the verb “give”:
    • “The police were given the information.” [14]
    • “The information was given to the police.” [14]
    • Other verbs that can have two objects include: ask, offer, pay, show, teach, and tell [14].

    Verbs Often Used in Passive

    • The sources include examples of verbs commonly used in the passive voice. These include: build, clean, damage, see, employ, invite, pronounce, lock, send, injure, need, take, bother, cover, steal, cancel, repair, restore, and many others [4, 6, 15-17].

    Other Notes

    • The sources clarify that in the passive form of doing/seeing etc., the form is being done / being seen [11].
    • The expression “I was born” is always used, not “I am born” [11].

    The passive voice is a fundamental aspect of English grammar, and the sources provide a comprehensive guide to its formation and proper usage.

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

  • Al Riyadh Newspaper, March 6, 2025 King Salman’s Humanitarian Efforts, Regional Issues, Development Projects

    Al Riyadh Newspaper, March 6, 2025 King Salman’s Humanitarian Efforts, Regional Issues, Development Projects

    These articles from “Al-Riyadh” newspaper cover a range of topics, primarily focusing on Saudi Arabia’s activities and initiatives both domestically and internationally during Ramadan. King Salman’s humanitarian efforts are highlighted through the distribution of dates to Muslims in numerous countries. The publication also reports on regional issues, including the Israeli blockade of Gaza and developments in the Syrian conflict. Domestically, articles discuss economic matters like gold prices and trade relations, social issues such as road safety and volunteer work during Ramadan, and development projects, including mosque renovations. Additionally, the paper features sports news, cultural commentary, and local announcements.

    Saudi Arabia: Key Issues and Initiatives

    Quiz

    Answer the following questions in 2-3 sentences each.

    1. According to the article, what has been a long-standing and firm issue for Saudi Arabia concerning Arab and Islamic nations?
    2. What specific demand regarding Palestinian territories has Saudi Arabia consistently voiced, as mentioned in the text?
    3. What was the main point of the resolution from the Arab and Islamic summit hosted by Saudi Arabia in November 2024?
    4. What is the purpose of the “King’s Gifts to Muslims in 102 Countries” program carried out during Ramadan?
    5. In which two countries were the Ramadan gift programs specifically mentioned as being implemented?
    6. What is the stated goal of the international conference “Building Bridges Between Islamic Sects” held in Mecca?
    7. Despite the ceasefire agreement mentioned in the context of Lebanon and Israel, what continued to occur?
    8. What did the Saudi delegation affirm at the Organisation for the Prohibition of Chemical Weapons in The Hague?
    9. What is the name of the campaign launched by the Emir of Qassim, and what is its primary objective?
    10. According to the article, what is the role of the General Authority for the Affairs of the Two Holy Mosques and the Prophet’s Mosque regarding I’tikaf (spiritual retreat) during Ramadan?

    Quiz Answer Key

    1. The article states that the Palestinian issue has been a long-standing and firm issue for Saudi Arabia, considered the primary concern of Arabs and Muslims, stemming from convictions based on the principle of justice and the right of the Palestinian people to their land.
    2. Saudi Arabia has consistently called for granting the Palestinian people their own independent state on the 1967 borders with Jerusalem as its capital.
    3. The main point of the resolution from the Arab and Islamic summit in November 2024, hosted by Saudi Arabia, was the rejection of the forced displacement of Palestinian citizens from the Gaza Strip and the West Bank, forming a fundamental reference for the Arab stance against Israeli and American policies on this issue.
    4. The purpose of the “King’s Gifts to Muslims in 102 Countries” program during Ramadan is to strengthen bonds of brotherhood and provide support to Muslims worldwide, sharing their joy during this holy month.
    5. The Ramadan gift programs were specifically mentioned as being implemented in Russia (Moscow) and Egypt (Cairo).
    6. The stated goal of the international conference “Building Bridges Between Islamic Sects” held in Mecca is to foster unity and understanding among different Islamic schools of thought and their scholars.
    7. Despite the ceasefire agreement between Hezbollah and Israel in November, Israeli airstrikes continued to target locations and facilities of Hezbollah in southern Lebanon and its east.
    8. The Saudi delegation at the Organisation for the Prohibition of Chemical Weapons in The Hague affirmed the Kingdom’s commitment to the provisions of the Chemical Weapons Convention.
    9. The campaign launched by the Emir of Qassim is called “100 Pilgrims,” and its primary objective is to enable those most in need to perform the rituals of Umrah during the holy month of Ramadan, promoting social solidarity.
    10. The General Authority for the Affairs of the Two Holy Mosques and the Prophet’s Mosque began receiving applications for I’tikaf in the Two Holy Mosques via its electronic portal, outlining the conditions and guidelines for those wishing to undertake the spiritual retreat during the last ten days of Ramadan.

    Essay Format Questions

    1. Analyze the key aspects of Saudi Arabia’s foreign policy regarding the Israeli-Palestinian conflict as presented in the article. Discuss the historical context, stated principles, and specific actions or resolutions mentioned to support your analysis.
    2. Examine the significance of the “King’s Gifts to Muslims” program during Ramadan. How does this initiative reflect Saudi Arabia’s role and responsibilities within the broader Muslim world, and what are the potential social and religious impacts of such programs?
    3. Discuss the factors contributing to the ongoing tensions and potential threats to peace in the regions surrounding Saudi Arabia, based on the information provided in the article regarding Lebanon, Israel, and the situation in Gaza.
    4. Evaluate the various initiatives and programs highlighted in the article that demonstrate Saudi Arabia’s commitment to its national development and international standing. Consider examples related to religious affairs, social welfare, and economic diversification.
    5. Based on the excerpts, discuss the role of Saudi Arabia in promoting Islamic solidarity and interfaith dialogue. Analyze the significance of hosting conferences like “Building Bridges Between Islamic Sects” and the broader implications for regional and global relations.

    Glossary of Key Terms

    • I’tikaf: An Islamic practice consisting of a period of retreat in a mosque for the purpose of worship and reflection, especially during the last ten days of Ramadan.
    • Ramadan: The ninth month of the Islamic calendar, observed by Muslims worldwide as a month of fasting, prayer, reflection, and community.
    • Umrah: An Islamic pilgrimage to Mecca that can be undertaken at any time of the year, distinct from the Hajj which has specific dates.
    • Palestinian Issue: Refers to the ongoing political conflict between Israelis and Palestinians over land and self-determination in the region of historical Palestine.
    • Two Holy Mosques (Al-Haramain Al-Sharifain): Refers to the two most sacred mosques in Islam, the Masjid al-Haram (Grand Mosque) in Mecca and the Al-Masjid an-Nabawi (Prophet’s Mosque) in Medina, both located in Saudi Arabia.
    • Ceasefire: An agreement to stop fighting, typically for a temporary period.
    • Chemical Weapons Convention: An international treaty that outlaws the production, stockpiling, and use of chemical weapons and their precursors.
    • Forced Displacement (Tehjeer): The involuntary movement of people from their homes or regions, often due to conflict, persecution, or policies.
    • Humanitarian Aid: Assistance given to people in need, especially in situations of crisis such as war, natural disasters, or famine, aimed at alleviating suffering and preserving human dignity.
    • Diplomatic Efforts: Actions taken by governments through negotiation and communication to manage international relations and resolve conflicts peacefully.

    Arabic News Review: Saudi Arabia and Global Affairs

    Here is a detailed briefing document summarizing the main themes and important ideas from the provided Arabic news excerpts:

    Briefing Document: Key Themes and Ideas in Recent Arabic News

    Date: October 26, 2023 (based on the provided issue date of March 6, 2025, but reflecting the news content’s likely timeframe) Source: Excerpts from “20707.pdf” ( جريدة الرياض – Al Riyadh Newspaper)

    Overall Theme: The excerpts cover a range of domestic and international news, with a strong emphasis on Saudi Arabia’s role in regional and global affairs, particularly concerning the Palestinian issue, humanitarian aid, religious initiatives during Ramadan, economic developments, and domestic progress in various sectors.

    Key Themes and Ideas:

    1. Saudi Arabia and the Palestinian Issue:

    • Principled and unwavering stance: Saudi Arabia maintains a long-standing and firm position on the Palestinian issue, considering it the “first cause” of Arabs and Muslims. This stance is based on the principle of justice and the rights of the Palestinian people.
    • Quote: “.” (The Kingdom – and still is – and throughout long decades, has had firm and resolute stances regarding the Palestinian issue, which is the first cause of Arabs and Muslims, and these stances stemmed from firm convictions based on the principle of justice and the right of the people, and this unwavering stance has been its destiny.)
    • Support for Palestinian statehood: The Kingdom calls for granting the Palestinian people their independent state on the 1967 borders with Jerusalem as its capital.
    • Quote: .” (Rather, it was accompanied by a clear voice calling for granting the Palestinian people their state and establishing their rights, the independent Palestinian state on the 1967 borders with Jerusalem as its capital.)
    • Rejection of forced displacement: The resolutions of the Arab and Islamic summit hosted by Saudi Arabia in November 2024 emphasized the rejection of the displacement of Palestinian citizens, considering it a fundamental reference for the Arab stance against Israeli and American plans regarding the Gaza Strip and the West Bank.
    • Quote: ” (We should not overlook the significance of the resolutions of the Arab and Islamic Summit hosted by the Kingdom in last November (2024), especially its resolution including the rejection of the displacement of Palestinian citizens; as it formed a fundamental reference for the Arab stance against clear Israeli and American trends regarding the displacement of Palestinians from the Gaza Strip and the situation in the West Bank and the annexation of Gaza… The Kingdom, with its partners in the ministerial committee… and the Arab and Islamic global alliance… launched an initiative… and hosted the first meeting in Riyadh with the participation of about 90 countries… considered an international conference and a clear indication of the sincere desire to establish peace and establish the [Palestinian] state.)

    2. Humanitarian Aid and Ramadan Initiatives:

    • Gifts from the King to Muslims globally: The Custodian of the Two Holy Mosques is providing gifts of dates to Muslims in 102 countries during the holy month of Ramadan. This aims to strengthen the bonds of brotherhood and support Muslims worldwide in celebrating the month.
    • Quote: ” (The Ministry of Islamic Affairs, Endowments, Dawah and Guidance continues to implement the program of distributing dates, the gift of the Custodian of the Two Holy Mosques, within an initiative it implements in (102) countries during the blessed month of Ramadan.)
    • Implementation in various countries: The distribution has already taken place in Russia and Egypt, with significant quantities of dates allocated to benefit tens of thousands of people.
    • Example: Five tons of dates were allocated for 20,000 people in Russia.
    • Continuation of Iftar and Date Distribution Programs: The Kingdom continues to implement programs for providing Iftar meals to those fasting and distributing dates during Ramadan in various countries like Kazakhstan.
    • Example: 10 tons of dates were provided to around 15,000 beneficiaries in Kazakhstan.
    • Aid to Sudan: The Kingdom has launched the third phase of a project to support food security in Sudan for 2025, distributing food baskets to displaced persons and returnees in several states.

    3. Religious and Cultural Initiatives:

    • Conference on Building Bridges Between Islamic Schools of Thought: A conference under the patronage of the Custodian of the Two Holy Mosques is being held in Mecca, organized by the Muslim World League, with the participation of prominent scholars and muftis from various Islamic schools of thought and regions.
    • Quote: “برعاية خادم الحرمين.. مؤتمر بناء الجسور بين المذاهب اإلسالمية ينطلق بمكة” (Under the patronage of the Custodian of the Two Holy Mosques… Conference on building bridges between Islamic schools of thought launches in Mecca.)
    • Development of Historical Mosques: The second phase of a project to develop historical mosques has been launched, including the renovation and restoration of 30 mosques in 10 regions, aiming to revive their role in worship and highlight the Kingdom’s cultural and historical depth.
    • “Alaa” Program: A program focusing on appreciating God’s blessings and raising religious and cultural awareness, involving media teams from Saudi Arabia and other Islamic countries.
    • Quote: (The message of the “Alaa” program focuses on the importance of reflecting upon the blessings that God has bestowed upon us, based on the noble Quranic verse: “So which of the favors of your Lord will you deny?” (Ar-Rahman: 13). The program aims to enhance religious and cultural awareness among the public.)
    • Increased Readiness at the Grand Mosque during Ramadan: The General Presidency for the Affairs of the Two Holy Mosques has increased its readiness to serve pilgrims and worshippers during Ramadan, with enhanced medical and ambulance teams.
    • Iftar Meal Distribution by Ikram Association: The Ikram Food Security Association in Mecca aims to distribute over a million Iftar meals during Ramadan, adhering to standards set by the General Presidency for the Affairs of the Two Holy Mosques.

    4. Economic Developments and Global Trade:

    • OPEC+ Decision on Oil Production: OPEC+ has decided to increase oil production for the first time since 2022, starting with a small increase in April. This follows previous significant production cuts.
    • Impact of US Tariffs: New US tariffs on imports from Mexico and Canada, as well as increased tariffs on Chinese goods, have come into effect, raising concerns about trade wars and their negative impact on global economic growth and inflation.
    • Quote: (A customs tariff of 25% on all imports from Mexico, a customs tariff of 10% on Canadian energy, and the doubling of customs duties on Chinese goods to 20% came into effect on Tuesday.)
    • Gold as a Safe Haven: Gold prices have seen fluctuations but generally remain sought after as a safe haven amid economic uncertainty and trade tensions.
    • Quote: (Tim Waterer, chief market analyst at KCM Trade, said, “I still expect gold to remain in demand while the state of uncertainty surrounding international trade remains a key characteristic and has entered the market.”)
    • Digital Marketing Trends in 2025: The digital marketing landscape is rapidly evolving, with increased reliance on data analysis, AI, personalized experiences, social commerce, and influencer marketing.

    5. Domestic Progress and Initiatives:

    • Najran Governor Reviews Civil Defense Report: The Governor of Najran province received the annual report of the Civil Defense Directorate in the region, commending their efforts in maintaining safety and security and preparing for natural and industrial hazards.
    • Eastern Province Governor Acknowledges Chamber of Commerce Achievements: The Governor of the Eastern Province reviewed the achievements of the Eastern Province Chamber of Commerce, particularly in training and supporting the business sector.
    • Qassim Governor Launches “100 Umrah Performers” Campaign: The Governor of Qassim launched an initiative to enable those in need to perform Umrah during Ramadan, highlighting the importance of social solidarity.
    • Deputy Governor of Mecca Inaugurates Quran Museum: The Deputy Governor of Mecca inaugurated the Holy Quran Museum, a major cultural and enriching destination showcasing the history and significance of the Quran using modern technologies.
    • Eastern Province Deputy Governor Reviews Youth Empowerment Initiatives: The Deputy Governor of the Eastern Province reviewed initiatives aimed at training and qualifying young men and women for the labor market.
    • Saudi Arabia’s Commitment to the Chemical Weapons Convention: The Kingdom’s delegation participated in the Executive Council meeting of the Organization for the Prohibition of Chemical Weapons in The Hague, reaffirming its commitment to the convention.
    • Progress in the Justice Sector: Saudi Arabia has made significant advancements in digitizing judicial services and enhancing real estate security through initiatives like the Real Estate Identity system.
    • Quote: (The Kingdom is considered one of the first countries that worked on them, and with the testimony of the World Bank, the Ministry was able, during the period between 2021 and 2024, to digitize more than 200 million judicial documents, linked to 250 courts and notary offices, and to understand what ranks Saudi Arabia in the justice sector globally, there is no harm in recalling the best global experiences in electronic services, such as the experiences of Estonia and South Korea…)
    • “Handicrafts Year 2025” Initiative: The year 2025 has been designated as the Year of Handicrafts in Saudi Arabia to preserve and promote traditional crafts as a vital part of the Kingdom’s cultural heritage.

    6. International Relations and Conflicts:

    • Stalled Peace Agreement in Southern Sudan: Developments threaten the peace agreement in South Sudan following the arrest of a senior SPLM-IO leader.
    • Lebanon and Syria Emphasize Border Control: The presidents of Lebanon and Syria met and stressed the “necessity” of controlling the borders between the two countries, particularly concerning smuggling.
    • Syria’s Participation in OPCW Meeting: The Syrian Foreign Minister announced his participation in a meeting of the Executive Council of the Organization for the Prohibition of Chemical Weapons, marking the first such participation since the ouster of Bashar al-Assad.

    7. Social and Cultural Commentary:

    • Ramadan as a Time for Reflection and Renewal: The excerpts highlight the spiritual and social significance of Ramadan, with discussions about changes in daily routines, the flourishing of literary gatherings, and the opportunity for inner purification.
    • Lebanese Drama Series “Bil-Dam” (With Blood): A Lebanese drama series dealing with sensitive social issues like child trafficking and illegal adoption is gaining attention.
    • Saudi Filmmaker at the Oscars: Saudi filmmaker Hakim Jomah attended the 97th Academy Awards, expressing his hope to participate as a nominee in the future and highlighting the growing potential of Saudi cinema.
    • Impact of Fasting on Health and Immunity: Articles discuss the health benefits of fasting during Ramadan, including its potential to enhance the immune system.
    • The Story of a Mosquito: An article reflects on the intricate creation of even small creatures like mosquitoes.

    8. Sports News:

    • Saudi Professional League Matches: Reports preview and cover matches in the Roshn Saudi League, including key fixtures involving Al-Ittihad, Al-Qadisiyah, Al-Khulood, and others, highlighting the competition for the league title and efforts to avoid relegation.
    • Al-Hilal’s Performance Dip: There is discussion about Al-Hilal’s recent decline in performance in both domestic and Asian competitions, despite a strong start to the season.
    • Real Sociedad vs. Manchester United in Europa League: A preview of the Europa League match between Real Sociedad and Manchester United, noting both teams’ struggles in their domestic leagues.
    • Al-Nassr’s Asian Champions League Ambitions: A mention of Al-Nassr’s need to win their second-leg match to qualify for the quarter-finals of the Asian Champions League.

    9. Other Notable Points:

    • Reopening of the Saudi Embassy in Somalia: The Saudi embassy in Somalia has officially reopened after being closed for several years.
    • Preparations for Itikaf in the Two Holy Mosques: The General Presidency for the Affairs of the Two Holy Mosques has begun receiving applications for Itikaf (seclusion for worship) in the Grand Mosque and the Prophet’s Mosque during the last ten days of Ramadan.
    • World Obesity Day: The Public Health Authority participated in World Obesity Day, raising awareness about healthy practices for children and combating obesity, aligning with the goals of Saudi Vision 2030.
    • Increased Demand for Traditional Pottery in Jazan during Ramadan: Markets in the Jazan region are witnessing increased demand for traditional pottery and handicrafts during the month of Ramadan.

    This briefing document provides a comprehensive overview of the key themes and important ideas presented in the provided news excerpts, highlighting Saudi Arabia’s multifaceted engagement on both domestic and international fronts.

    Saudi Arabia: Foreign Policy, Humanitarian Aid, and Cultural Initiatives

    FAQ on Themes and Ideas from the Provided Sources

    Q1: What are the main foreign policy stances of Saudi Arabia as highlighted in the excerpts, particularly concerning the Palestinian issue? Saudi Arabia maintains a firm and unwavering stance on the Palestinian issue, viewing it as the primary concern for Arabs and Muslims. This position is rooted in principles of justice and the right of the Palestinian people to their own independent state, with borders based on the 1967 lines and East Jerusalem as its capital. The Kingdom has consistently provided diplomatic and political support, as well as extensive humanitarian and relief aid to Palestinians. It has also vocally advocated for Palestinian rights on the international stage. Furthermore, Saudi Arabia hosted and played a significant role in the Arab and Islamic Summit in November 2024, which notably rejected the forced displacement of Palestinians.

    Q2: How does Saudi Arabia demonstrate its commitment to Muslims worldwide during the month of Ramadan, according to the text? During Ramadan, Saudi Arabia implements several initiatives to support Muslims globally. The “Custodian of the Two Holy Mosques’ Gift Program” distributes dates to Muslims in 102 countries to foster brotherhood and share the joy of the holy month. This program is executed through Saudi embassies, such as in Moscow and Cairo, reaching tens of thousands of individuals. Additionally, the Kingdom continues its program for Iftar meals for those fasting. These efforts reflect Saudi Arabia’s leading humanitarian and pioneering role in supporting Muslims around the world during Ramadan, a commitment acknowledged and appreciated by religious leaders and communities internationally.

    Q3: What was the purpose and significance of the “Building Bridges Between Islamic Sects” conference held in Mecca? Sponsored by the Custodian of the Two Holy Mosques and organized by the Muslim World League, the second edition of the “Building Bridges Between Islamic Sects” international conference in Mecca aimed to foster understanding and unity among various Islamic schools of thought and their scholars. The conference, attended by prominent Muftis and scholars from over 90 countries representing diverse Islamic مذاهب and schools, underscores Saudi Arabia’s commitment to promoting dialogue and cooperation within the Islamic world. It is considered a global initiative and a testament to the sincere desire to establish peace and build bridges among different Islamic perspectives.

    Q4: What are some of the humanitarian efforts undertaken by Saudi Arabia, specifically mentioning the initiatives highlighted in the text? Saudi Arabia engages in various humanitarian efforts, particularly focused on supporting Muslims and others in need. These include the distribution of dates to 102 countries during Ramadan, providing Iftar meals for those fasting, and delivering food baskets to those affected by crises, such as in Sudan. The Kingdom also launched the “100 Umrah Pilgrims” campaign in the Qassim region, facilitating Umrah for those with the greatest need during Ramadan. Moreover, Saudi Arabia is actively involved in addressing the humanitarian crisis in Gaza, condemning the obstruction of aid and supporting the Palestinian people. These diverse initiatives demonstrate a broad commitment to humanitarian principles and providing essential assistance on both regional and global scales.

    Q5: What are the key features and objectives of Saudi Arabia’s initiatives related to the development and preservation of historical and religious sites? Saudi Arabia places significant emphasis on the development and preservation of its historical and religious heritage. The initiatives include the rehabilitation and restoration of historical mosques across 10 regions, aiming to preserve their architectural authenticity, cultural significance, and role in worship. The opening of the Holy Quran Museum in Mecca showcases a comprehensive collection that integrates knowledge with modern technologies, offering an interactive experience for visitors to learn about the Quran’s history and the care it has received. These efforts align with Saudi Vision 2030, which focuses on preserving national heritage and highlighting the Kingdom’s cultural and historical dimensions.

    Q6: How is Saudi Arabia leveraging digital technology and innovation to enhance services and achieve its Vision 2030 goals, as seen in the provided excerpts? Saudi Arabia is actively integrating digital technology and innovation across various sectors to improve efficiency and meet the objectives of Vision 2030. In the justice sector, over 200 million judicial documents have been digitized, enhancing the security and reliability of real estate ownership through initiatives like the Real Estate Identity. The General Authority for Food and Drug Administration is using digital platforms to raise health awareness. Furthermore, the digital transformation extends to the management of Hajj and Umrah, with online platforms for Itikaf registration at the Two Holy Mosques. These examples illustrate a broad commitment to leveraging technology to streamline processes, improve services, and achieve the strategic goals of Vision 2030.

    Q7: What are the main challenges and ongoing conflicts discussed in the text that involve regional and international actors? The excerpts highlight several ongoing conflicts and challenges with regional and international implications. The Israeli-Palestinian conflict remains a central issue, with continued blockades of aid to Gaza and military operations. The conflict between Hezbollah and Israel persists despite ceasefire attempts. In South Sudan, the peace agreement faces threats due to ongoing instability and potential for renewed conflict. Additionally, the civil war in Sudan continues to cause a severe humanitarian crisis. The conflict in Ukraine also features, with discussions around NATO’s role and the potential for escalation. These situations involve various regional and global actors and present significant challenges to peace and stability.

    Q8: How is the concept of cultural heritage and its preservation being emphasized in Saudi Arabia, as indicated in the excerpts? Saudi Arabia is actively emphasizing the importance of cultural heritage and its preservation. The year 2025 has been designated as the “Year of Handicrafts,” underscoring the cultural and economic significance of traditional crafts. This initiative aims to recognize artisans, preserve traditional skills from being lost to globalization, and celebrate handicrafts as an integral part of national heritage. The establishment of the “Aaysaan” project in Diriyah, the birthplace of the first Saudi state, aims to build a generation that values its heritage and transmits it to future generations, aligning with Vision 2030’s focus on strengthening national identity and highlighting the Kingdom’s cultural depth. These efforts demonstrate a commitment to safeguarding and promoting Saudi Arabia’s rich cultural legacy.

    The Observance and Significance of Ramadan

    Based on the sources, Ramadan is a significant month with various activities centered around religious observance, charity, community engagement, and personal reflection.

    Religious Observances: The most central activity during Ramadan is fasting (Sawm), which is the fourth pillar of Islam. This involves abstaining from food and drink from dawn till dusk and is considered to have both spiritual and health benefits.

    Charitable Activities: The sources highlight significant charitable efforts undertaken during Ramadan. The Kingdom of Saudi Arabia actively distributes dates and iftar meals to Muslims in various countries, including Cameroon, Gabon, and Kazakhstan, during the holy month. This initiative is part of the Kingdom’s ongoing support for its brethren. Additionally, food baskets are distributed to the needy in locations such as the suburbs of Damascus in Syria, central Java in Indonesia, and Albasan Governorate in Albania.

    Community and Social Engagement: Even in non-Islamic countries where Eid al-Fitr and Eid al-Adha are not official holidays, Muslims organize Eid prayers and gatherings in mosques or open spaces. They also maintain traditions like family visits and exchanging greetings. Due to geographical distances, modern communication methods like phone and video calls are used to share Eid moments with relatives in their home countries.

    Spiritual Reflection and Development: Ramadan is described as a month that enriches the soul, with altered patterns of reading and writing. It is a time for contemplation and renewal, not just on a religious level but also intellectually. Sufis seek closeness to God during this month. The fasting experience is portrayed by Saudi poets and writers as a time for reflective engagement with life. Islamic organizations support projects that positively impact the daily lives of Muslims and promote Islamic values during Ramadan.

    Managing Daily Life and Productivity: The change in daily routines during Ramadan requires effective time management to maintain productivity. Some companies in certain countries reduce working hours to allow employees to redistribute their efforts more efficiently. Maintaining healthy habits during fasting is crucial for sustaining energy and focus.

    I’tikaf: For those in Saudi Arabia, a service is available to issue permits for I’tikaf, which is seclusion in a mosque, during the last ten days of Ramadan.

    Cultural Significance: The inauguration of the Holy Quran Museum in Mecca coincides with this period, underscoring the emphasis on religious heritage. Traditional handicrafts are also part of the cultural landscape, with potential for increased activity or appreciation during Ramadan.

    In summary, Ramadan is depicted as a multifaceted month characterized by intense religious devotion through fasting and prayer, significant charitable activities, strong community bonds, a focus on spiritual and intellectual reflection, adjustments to daily routines and productivity, and a heightened appreciation for religious culture and heritage.

    Ramadan Food Aid Distribution: Global Efforts and Obstacles

    Based on the sources and our previous discussion, the distribution of food aid is a prominent activity, particularly during the month of Ramadan.

    Key aspects of food aid distribution highlighted in the sources:

    • Distributors: The Kingdom of Saudi Arabia is a major contributor to food aid distribution. The Custodian of the Two Holy Mosques initiates programs to provide aid to Muslims in numerous countries. The Ministry of Islamic Affairs, Dawah and Guidance is involved in implementing these programs, specifically the distribution of dates. The King Salman Humanitarian Aid and Relief Centre acts as the Kingdom’s arm for humanitarian and relief efforts, working to alleviate the suffering of the needy and afflicted.
    • Types of Aid: Dates are a specific type of food aid frequently distributed by Saudi Arabia during Ramadan. The provision of iftar meals is also a part of the Kingdom’s charitable activities during the holy month, as mentioned in our previous conversation. Food baskets are also distributed to those in need in various locations [our conversation history].
    • Beneficiaries and Locations: Food aid reaches Muslims in various countries around the world. Specific examples mentioned in the sources and our history include Russia, Egypt, Hungary, Cameroon, Gabon, Kazakhstan [our conversation history], suburbs of Damascus in Syria, central Java in Indonesia, and Albasan Governorate in Albania [our conversation history]. The aim is to support Muslims and share their joy during Ramadan.
    • Purpose: The distribution of food aid aims to strengthen bonds of brotherhood and provide support to Muslims globally. It is an expression of the continuous charitable giving of the Custodian of the Two Holy Mosques to brethren. The broader goal is to alleviate the suffering of the needy and afflicted in various parts of the world.
    • Challenges: In contrast to the distribution efforts, one source highlights the prevention of aid from entering Gaza by the occupation, leading to the return of famine conditions. This underscores that while aid is being distributed in many places, there are also significant obstacles to delivering essential food supplies in certain critical areas.

    In summary, the distribution of food aid, particularly dates and iftar meals, is a significant charitable undertaking by Saudi Arabia during Ramadan, reaching numerous Muslim communities worldwide. However, the sources also point to the unfortunate reality of aid blockades preventing essential supplies from reaching those in dire need, such as in Gaza.

    Global Diplomatic, Humanitarian, and Political Affairs

    Based on the sources and our previous discussion, several aspects of international relations are evident:

    • Diplomatic Efforts and Conflict Resolution: The Kingdom of Saudi Arabia is actively involved in international diplomacy, as seen in its efforts to address the crisis in Sudan. The Kingdom aims to achieve a ceasefire, stability, the return of displaced persons, and a political future that safeguards Sudan’s security, sovereignty, unity, and stability while preventing external interference. This highlights a proactive role in regional conflict resolution.
    • Humanitarian Aid and International Solidarity: The sources emphasize the Kingdom of Saudi Arabia’s significant role in providing humanitarian aid to various countries. This is exemplified by the distribution of dates and iftar meals to Muslims in 102 countries during Ramadan. This initiative, carried out by the Ministry of Islamic Affairs, Dawah and Guidance and supported by the directives of the leadership, aims to strengthen bonds of brotherhood and provide support to Muslims worldwide. Countries like Kazakhstan have expressed their deep appreciation for this continuous charitable giving, highlighting the strengthening of bilateral relations through aid. The King Salman Humanitarian Aid and Relief Centre is also a key organization in the Kingdom’s international humanitarian efforts.
    • Islamic Cooperation and Unity: The Muslim World League plays a role in fostering unity among Islamic schools of thought, building bridges, and coordinating stances to address common challenges. It aims to promote moderation and counter sectarianism. Similarly, the University of Islamic Jurisprudence works to coordinate positions among forces of Islamic moderation to serve the Islamic nation and confront extremism. The expressions of thanks and appreciation from scholars worldwide to the Custodian of the Two Holy Mosques and the Crown Prince underscore the recognition of their efforts in supporting Islam and Muslims globally.
    • Regional Conflicts and Security Concerns: The sources report on Israeli airstrikes in southern Lebanon, indicating ongoing regional tensions and security issues. Additionally, there are reports about the prevention of aid from entering Gaza, highlighting the severe humanitarian consequences of the ongoing conflict and occupation. The situation in South Sudan, with the arrest of a senior military official, also points to internal conflicts with potential regional implications.
    • International Agreements and Organizations: The participation of Syria in a meeting of the Organisation for the Prohibition of Chemical Weapons (OPCW) in The Hague demonstrates engagement with international regulatory bodies. The Kingdom of Saudi Arabia’s reaffirmation of its commitment to the Chemical Weapons Convention and its support for resolving the Syrian chemical file highlight the importance of international agreements in maintaining global security.
    • Global Economy and Trade Relations: Discussions about oil markets and the impact of US tariffs and retaliatory tariffs illustrate the interconnectedness of the global economy and the potential for trade disputes to affect international relations. The consideration by Japan and South Korea to increase imports of US natural gas indicates evolving energy security strategies and trade partnerships.
    • Bilateral Relations: The congratulatory message sent by the Crown Prince to the Austrian Chancellor on the formation of the new government is an example of routine diplomatic engagement and the maintenance of bilateral relations between nations.
    • Proposed Approaches to International Conflicts: Former US President Trump’s proposed three-pronged approach to the Ukraine-Russia conflict provides an example of different perspectives and strategies for addressing major international conflicts, involving diplomatic pressure, the role of proxy actors, and the involvement of international alliances like NATO.
    • Impact of Internal Political Processes on International Relations: The announcements regarding the postponement of elections in Libya and the setting of new dates demonstrate how internal political developments within a country can have implications for its international standing and relationships.

    In summary, the sources reveal a complex web of international relations involving diplomatic efforts, humanitarian aid, religious cooperation, regional conflicts, adherence to international agreements, economic interdependence, and bilateral engagements. The Kingdom of Saudi Arabia emerges as a significant actor in these relations, actively engaged in conflict resolution, providing substantial humanitarian assistance, and fostering Islamic unity. However, the sources also highlight ongoing challenges such as regional conflicts and obstacles to delivering aid in certain areas.

    Insights on Health, Safety, and Well-being

    Based on the sources, several aspects related to health and safety are discussed:

    • Health Benefits of Fasting: Source and discuss the health aspects of fasting during Ramadan. Fasting can be motivated by religious reasons or for physical health. It is considered one of the main methods to maintain the body’s overall health and is seen as a form of an important dietary regimen. Recent studies mentioned in indicate that regular fasting for extended periods can help improve general health and maintain a healthy body weight. Furthermore, fasting may increase the efficiency of immune cells, such as white blood cells and T-cells, contributing to the body’s ability to activate immune responses and resist foreign bodies. The body may initially destroy some white blood cells during fasting to provide energy, but it quickly returns to stimulate the production of new cells, thereby enhancing the immune system’s efficiency. A study in the “Immunity and Ageing” journal suggests that intense fasting for specific periods stimulates the efficiency of the immune system by activating the complement system on the surface of red blood cells, potentially helping to eliminate infections. Another study in “Cell Report” indicated that fasting increases levels of Arachidonic Acid, which can help reduce excessive immune responses, potentially lowering the risk of autoimmune diseases. Source mentions the saying “fast to be healthy,” linking fasting to overall well-being.
    • Importance of Diet During Ramadan: Source and highlight the significance of breaking the fast with dates and water. Dates are rich in nutrients, fiber, vitamins, and minerals that support body health and are an ideal choice to break the fast, minimizing digestive issues. Drinking water at regular intervals between iftar and suhoor is crucial for maintaining fluid balance, preventing dehydration, and reducing feelings of thirst and fatigue.
    • Public Safety and Civil Defense: Source emphasizes the importance of preventative measures and public safety for preserving lives and property in the Najran region and its governorates. The text mentions the efforts of Civil Defense personnel and the necessity of preparedness to deal with natural and industrial hazards and the development of civil protection plans.
    • Occupational Safety: Source reports an incident in southern Lebanon where two brothers working on collecting scrap metal were injured in Israeli strikes, highlighting the dangers present in conflict zones and the risks faced by civilians.
    • Road Safety: Source mentions traffic accidents as one type of case that might be handled by a potential virtual judge, implying the ongoing issue of road safety and the legal processes involved in accidents.
    • Health Awareness and Education: Source underscores the importance of health awareness in children, particularly regarding healthy habits like drinking water and natural juices instead of sugary drinks and reducing the consumption of fast food, which are considered major factors contributing to increasing rates of obesity and related health problems in children. It also advises on healthier cooking methods like grilling and baking instead of frying.
    • Workplace Health and Productivity During Ramadan: Source,, and discuss the perception that work efficiency might decrease during Ramadan due to fasting. However, it argues that if individuals focus on the benefits of fasting, manage their time effectively, maintain a healthy diet during non-fasting hours, and get sufficient rest, they can sustain their work performance. Some companies even reduce working hours to improve efficiency. The text emphasizes that maintaining healthy habits during Ramadan ensures the continuation of work with the same quality. It also notes that fasting can help the body eliminate toxins and promote a feeling of lightness and activity with a balanced diet. Addressing issues like headaches, often caused by insufficient water intake, and avoiding heavy meals at iftar are important for maintaining well-being during the working day.

    In summary, the sources touch upon various aspects of health and safety, including the physiological effects and potential benefits of fasting during Ramadan, the importance of dietary choices and hydration, public safety measures and civil defense preparedness, occupational hazards in conflict zones, road safety concerns, the need for health awareness and education, particularly for children, and strategies for maintaining workplace health and productivity while fasting.

    Global Economic Trends and Sector Developments

    Based on the sources, several aspects of economic impacts are discussed:

    • Impact of Tariffs and Trade Relations: The imposition of tariffs by the United States on goods from Canada, Mexico, and China is a recurring theme, with potential significant economic impacts. These tariffs, such as the 25% tariff on all imports from Mexico and the 10% tariff on Canadian energy and the doubling of tariffs on Chinese goods to 20%, are expected to slow economic growth and reduce demand for fuel. Concerns also exist that these actions could reignite a trade war and escalate global inflation. Retaliatory tariffs imposed by countries like Canada on American imports and by China on US agricultural products are also noted. These trade tensions create uncertainty in the global economy, potentially impacting investment and consumer behavior. The potential for tariffs to push inflation higher is also highlighted. However, in times of economic uncertainty caused by tariffs, gold can become a safe-haven asset, increasing its attractiveness.
    • Oil Markets and Production: The sources discuss the stabilization of oil prices after reaching low levels due to concerns about the impact of US tariffs on economic growth and fuel demand. The decision by OPEC+ (including Russia) to increase oil production for the first time since 2022 is reported. This small increase of 138,000 barrels per day starting in April marks a step towards potentially reversing larger previous production cuts. However, the market remains under pressure with the anticipation of this increased production and the potential return of Russian oil supplies due to optimism about a resolution in the Ukraine conflict. China, a major oil importer, has set an economic growth target of around 5% for 2025 and is implementing stimulus measures, which could influence oil demand. Changes in Venezuelan oil exports and US policy towards Chevron’s operations in Venezuela are also noted as factors affecting the global oil market.
    • Growth of Digital Marketing: The sources indicate the tremendous evolution of digital marketing driven by technological advancements and changing consumer habits. Digital marketing is no longer just an option but a necessity for organizations. Innovations like content marketing, artificial intelligence (AI), and integrated electronic commerce experiences are making digital marketing more intelligent and effective. AI, through machine learning algorithms, enables personalized recommendations, customer service via chatbots, and automation of marketing processes, enhancing efficiency and return on investment. High-quality content creation and search engine optimization (SEO) are also crucial drivers in digital marketing.
    • Development of the Saudi Arabian Furniture Industry: The furniture industry in the Kingdom of Saudi Arabia is identified as an important sector reflecting the society’s aesthetic taste and interest in functionality. The sector has witnessed significant development in recent years, blending heritage with modernity to create a unique identity. Saudi furniture is being exported to various countries, enhancing the Kingdom’s position in design and manufacturing. The industry emphasizes its connection to cultural identity and local heritage, incorporating traditional motifs and using high-quality local materials. Innovation in sustainable materials and alignment with global trends while preserving national identity are also key features.
    • Economic Significance of Cultural and Creative Industries: The sources highlight the cultural and creative industries and handicrafts as significant sectors of the global economy and trade, offering new opportunities for developing countries. Handicrafts, in particular, represent a substantial portion of global output, with a continuous increase. The transition towards viewing cultural heritage as a basis for creative industries is considered highly important for economic transformation.
    • Economic Impact of Health Issues: Source mentions that the increasing rate of obesity in children has health and related problems and requires societal awareness. While not explicitly detailed, health issues like obesity can have long-term economic impacts on healthcare costs and productivity.

    In summary, the sources highlight significant economic impacts arising from international trade policies, particularly the US tariffs and retaliatory measures, which create uncertainty and can affect growth and inflation. The oil market remains a crucial area with its dynamics influenced by production decisions and geopolitical factors. Simultaneously, sectors like digital marketing, the Saudi Arabian furniture industry, and cultural and creative industries are experiencing growth and contributing to the economy. Health-related issues also carry potential long-term economic implications.

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

  • C++ Programming: Code Examples, Tutorials, and Problem Solving

    C++ Programming: Code Examples, Tutorials, and Problem Solving

    These sources offer a comprehensive introduction to C++ programming concepts for beginners. They cover fundamental topics like setting up the development environment, understanding variables, data types, operators, and control flow statements like ‘if-else,’ loops, and switch cases. The sources also discuss functions, including function overloading and recursion, illustrating how to build practical applications such as a calculator, a BMI calculator, and games. Additionally, there’s exploration of drawing shapes and the use of loops for generating multiplication tables, providing hands-on examples to reinforce learning. Finally, generics and templates are introduced to highlight programming best practices and how to improve code reusability.

    C++ Fundamentals Study Guide

    Quiz

    1. What is the purpose of the ASCII table? The ASCII table provides a numeric representation for characters, allowing computers to distinguish between letters, numbers, and symbols by assigning each a unique numerical code. This enables computers to process and store text.

    2. How many characters can ASCII represent, and why is this sometimes a limitation? Standard ASCII can represent 128 characters because it uses 7 bits per character. This is a limitation because it is sufficient for English characters but doesn’t include the characters needed to represent many other languages.

    3. Explain the difference between char and int data types in the context of ASCII representation. A char data type stores a single character, while an int data type stores an integer number. In the context of ASCII, a char variable can hold a character, and an int variable can hold the corresponding ASCII code of that character, allowing conversions between them using casting operators.

    4. What is a casting operator, and how is it used to convert between characters and their ASCII values? A casting operator is a way to explicitly convert one data type into another. In C++, you can use (int)character to get the ASCII value of a character or (char)number to get the character represented by an ASCII number.

    5. Describe the purpose of the modulo operator (%) and give an example of its use. The modulo operator (%) returns the remainder of a division. For example, 5 % 2 equals 1, because 5 divided by 2 is 2 with a remainder of 1.

    6. Explain how the modulo operator can be used to determine if a number is even or odd. If a number modulo 2 equals 0, the number is even; if it equals 1, the number is odd. This is because even numbers are perfectly divisible by 2, leaving no remainder, while odd numbers leave a remainder of 1.

    7. What is the difference between the = operator and the == operator in C++? The = operator is the assignment operator, used to assign a value to a variable (e.g., x = 5). The == operator is the equality operator, used to compare two values for equality (e.g., x == 5).

    8. What is the difference between pre-increment (++x) and post-increment (x++) operators? The pre-increment operator (++x) increments the variable’s value before it is used in the expression, while the post-increment operator (x++) increments the variable’s value after it has been used in the expression. For example, if x is 5, y = ++x will result in x being 6 and y being 6, but y = x++ will result in x being 6 and y being 5.

    9. Name three relational operators in C++ and provide an example of how they are used. Three relational operators in C++ are:

    • < (less than): if (a < b)
    • > (greater than): if (x > y)
    • == (equal to): if (num == 10)

    10. Explain the purpose of the break statement in a switch statement. The break statement terminates the execution of the current case in a switch statement and transfers control to the statement immediately following the switch block. Without a break statement, execution would “fall through” to the next case, even if its condition is not met.

    Essay Questions

    1. Discuss the importance of understanding the underlying numeric representation of characters (like ASCII) when developing software applications. Give examples of situations where this knowledge could be crucial for solving a programming problem.
    2. Explain the concept of operator precedence in C++. Describe how different types of operators (arithmetic, relational, logical, assignment) interact within a complex expression, and how parentheses can be used to control the order of evaluation.
    3. Compare and contrast the while loop, the for loop, and the do-while loop in C++. Provide scenarios where one type of loop might be more appropriate than the others.
    4. Discuss the advantages of using functions in C++ programming. Explain how functions can improve code readability, reusability, and maintainability, and illustrate your points with examples.
    5. Explain the concept of object-oriented programming. Discuss the differences between classes and objects.

    Glossary

    • ASCII: (American Standard Code for Information Interchange) A character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices. Each character is assigned a unique number.
    • Casting Operator: An operator that converts a value from one data type to another. For example, converting an int to a char.
    • Modulo Operator (%): An arithmetic operator that returns the remainder of a division.
    • Variable: A named storage location in a computer’s memory that can hold a value.
    • Data Type: A classification of data that tells the compiler how the programmer intends to use the data. Examples include int, char, float, and bool.
    • Operator Precedence: The order in which different operators are evaluated in a complex expression.
    • Loop: A programming construct that repeats a block of code multiple times.
    • While Loop: A control flow statement that executes a block of code repeatedly as long as a specified condition is true.
    • For Loop: A control flow statement for specifying iteration, which allows code to be executed repeatedly.
    • Do-While Loop: A control flow statement similar to a while loop, except that its condition is tested at the end of the loop body, ensuring that the loop body is always executed at least once.
    • Function: A block of organized, reusable code that is used to perform a single, related action.
    • Return Type: Specifies the data type of the value that a function returns after its execution.
    • Parameter: A value that is passed into a function when it is called.
    • Arguments: The actual values passed to a function when it is invoked.
    • Object-Oriented Programming: A programming paradigm based on the concept of “objects”, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.
    • Classes: A blueprint for creating objects. It defines the attributes and methods that objects of that class will have.
    • Objects: An instance of a class. It is a concrete entity that has attributes and can perform methods.
    • Pointers: A variable that stores the memory address of another variable.
    • Void Pointers: Pointers that can point to any data type. They are useful for generic programming.
    • Recursion: A method of solving a problem where the solution depends on solutions to smaller instances of the same problem.

    C++ Programming Fundamentals: A Comprehensive Guide

    Okay, here’s a briefing document summarizing the key themes and ideas from the provided source “01.pdf”:

    Briefing Document: C++ Programming Concepts

    Overview:

    The source material appears to be a C++ programming tutorial covering fundamental concepts, including ASCII representation of characters, casting, basic input/output, arithmetic operators, logical operators, assignment operators, conditional statements (if/else, switch), loops (while, for, do-while), functions (including recursion), pointers, and object-oriented programming principles. The material uses practical examples (e.g., building a cipher, determining even/odd numbers, calculating triangle types, drawing shapes) to illustrate these concepts.

    Main Themes & Ideas:

    • ASCII and Character Representation:
    • Characters in C++ are represented by numerical codes using the ASCII standard. The source highlights the difference between uppercase and lowercase letters having distinct ASCII values.
    • Quote: “each character has its numeric pair inside ask key table… lowercase letter a is 97… capital letter A… 65… computer can distinguish between lowercase and uppercase letters.”
    • Casting operators can be used to convert between characters and their corresponding ASCII integer values.
    • Quote: “you can get an idea on how you can build something more useful than than just basic hello world application so you can for example build a program that ciphers words and sentences in a s key.”
    • Basic Input and Output:
    • std::cout is used for outputting text and variable values to the console.
    • std::cin is used for reading input from the user.
    • The tutorial demonstrates how to chain cout and cin operators to input or output multiple variables in a single line.
    • Arithmetic, Relational, Logical, and Assignment Operators:
    • The source covers various operators including modulo (%), increment/decrement (++, –), relational operators (<, >, ==, !=, <=, >=), logical operators (&&, ||, !), and assignment operators (=, +=, -=, *=, /=, %=).
    • It explains the difference between pre-increment/decrement and post-increment/decrement.
    • Quote: “…this operator here gives you the remainder of dividing these two numbers…” (referring to modulo).
    • Operator precedence is briefly touched upon: arithmetic > relational > logical.
    • Conditional Statements (if/else, switch):
    • if and else statements are used to execute different code blocks based on a condition.
    • The tutorial shows how to nest if/else statements.
    • switch statements are used for multi-way branching based on the value of a variable. The break statement is essential to prevent fall-through to subsequent case labels.
    • Quote: “this break keyword is really used so that our switch case statement knows where our first case ends.”
    • Loops (while, for, do-while):
    • while loops execute a block of code repeatedly as long as a condition is true. The source emphasizes the importance of ensuring the loop condition eventually becomes false to avoid infinite loops.
    • for loops provide a concise way to iterate a specific number of times. Nested for loops are used to create patterns and shapes.
    • do-while loops are similar to while loops, but the code block is executed at least once before the condition is checked.
    • Functions:
    • Functions are reusable blocks of code that perform a specific task. The source covers defining functions, passing arguments, and returning values.
    • Quote: “…this main function here is much more clean than it was before…” (referring to using functions to improve code organization).
    • Recursion: The tutorial explains recursion where a function calls itself. A base case is crucial to prevent infinite recursion and stack overflow errors.
    • Pointers:
    • Pointers are variables that store memory addresses.
    • The & operator is used to get the address of a variable.
    • The * operator is used to declare a pointer and to dereference a pointer (access the value at the stored address).
    • Pointers must be of the same type as the variable they point to (with the exception of void pointers).
    • Quote: “your pointer has to be of the same type like the variable that it is pointing to”.
    • Void Pointers: These can point to variables of any data type but must be cast to a specific type before dereferencing.
    • Quote: “a void pointer is a special type of pointer that can hold the address of a variable of any other data type”.
    • Object-Oriented Programming (OOP):
    • The source briefly introduces OOP, stating that it allows representing real-life objects with their attributes and behaviors.
    • Classes and objects are mentioned as fundamental concepts.

    Illustrative Examples:

    • Cipher: Creating a program to convert words into ASCII codes and vice-versa.
    • Even/Odd Checker: Determining if a number is even or odd using the modulo operator.
    • Triangle Classifier: Determining if a triangle is equilateral, isosceles, or scalene based on side lengths.
    • Shape Drawing: Using nested loops to draw rectangle shapes.
    • Digit Counter: Counting the number of digits in a number using a while loop.
    • Pin Verification: A do-while loop is used to allow a user a limited number of attempts to enter a correct PIN.
    • Prime Number Checker: Creating a function to determine if a given number is a prime.
    • Summing Numbers with Recursion: Demonstrates a recursive function to sum a range of numbers.

    Key Quotes:

    • “each character has its numeric pair inside ask key table… lowercase letter a is 97… capital letter A… 65… computer can distinguish between lowercase and uppercase letters.”
    • “…this operator here gives you the remainder of dividing these two numbers…” (referring to modulo).
    • “this break keyword is really used so that our switch case statement knows where our first case ends.”
    • “…this main function here is much more clean than it was before…” (referring to using functions to improve code organization).
    • “a void pointer is a special type of pointer that can hold the address of a variable of any other data type”.
    • “your pointer has to be of the same type like the variable that it is pointing to”.

    Potential Use:

    This document can serve as a quick reference or study guide for individuals learning C++ programming, covering many of the essential building blocks of the language.

    Programming Concepts: Answering Common Questions

    FAQ on Programming Concepts

    • What is the ASCII key table, and how is it used to represent characters in a computer?
    • The ASCII (American Standard Code for Information Interchange) key table is a standard that assigns a unique numeric value to each character, including letters (uppercase and lowercase), numbers, and some special symbols. This allows computers to store and process text by representing characters as numbers. For example, ‘a’ is represented as 97 and ‘A’ is represented as 65.
    • How can you convert between characters and their corresponding ASCII values in C++?
    • In C++, you can convert a character to its ASCII value by using a casting operator, like int(character). Conversely, you can convert an ASCII value back to its character representation by using char(numericValue).
    • What is the modulo operator (%) used for, and how can it be applied to determine if a number is even or odd?
    • The modulo operator (%) returns the remainder of a division. For example, 5 % 2 equals 1 because 5 divided by 2 is 2 with a remainder of 1. To check if a number is even or odd, you can use the modulo operator with 2. If number % 2 equals 0, the number is even; otherwise, it’s odd.
    • What are increment and decrement operators in C++, and what is the difference between pre-increment/decrement and post-increment/decrement?
    • Increment (++) and decrement (–) operators are used to increase or decrease the value of a variable by 1, respectively. Pre-increment/decrement modifies the value of the variable before it is used in the expression, while post-increment/decrement modifies the value after it is used. For example, if counter = 7, ++counter would result in counter being 8, and the expression would evaluate to 8. Whereas counter++ would also increment counter to 8, but the expression would evaluate to 7.
    • What are relational and logical operators in C++, and how are they used?
    • Relational operators (e.g., <, >, <=, >=, ==, !=) compare the values of two operands and return a Boolean value (true or false) based on the relationship. Logical operators (AND &&, OR ||, NOT !) combine two or more conditions into a single condition. Relational operators are used to compare numerical and string values, while logical operators are used for flow control.
    • What is the purpose of a switch statement, and how does the break keyword work within it?
    • A switch statement is a control structure that allows you to execute different blocks of code based on the value of a variable. The break keyword is crucial because it terminates the execution of a case within the switch statement. Without break, the code will “fall through” to the next case, potentially executing unintended code.
    • What are loops used for in programming, and how do while, do-while, and for loops differ in C++?
    • Loops are used to execute a block of code multiple times. while loops execute as long as a specified condition is true, checking the condition before each execution. do-while loops are similar to while loops, but they execute the block of code at least once, checking the condition at the end of each execution. for loops are designed for executing a block of code a specific number of times, typically using a counter variable that is initialized, checked against a condition, and incremented/decremented in each iteration.
    • What are functions, and how do they contribute to code reusability and modularity?
    • Functions are self-contained blocks of code designed to perform a specific task. They accept input (parameters), process it, and may return a result. Functions promote code reusability by allowing you to use the same block of code multiple times without rewriting it. They also contribute to modularity by breaking down complex problems into smaller, manageable parts, making the code easier to understand, test, and maintain.

    Visual Studio: A Beginner’s Guide

    Here’s what the sources say about Visual Studio:

    • Visual Studio 2019 is a tool used for C++ programming.
    • It is an IDE (integrated development environment), meaning it has many options, including ones that are useful for beginners.
    • The Community version can be downloaded and used for free, and there are many tutorials available on YouTube that explain how to download and install it.
    • When Visual Studio is opened, recent projects are displayed on the left.
    • On the right, there is a menu with multiple options: checking out code from GitHub, opening an existing project, and creating a new project.
    • To create a new project, the project type must be defined. For beginners, a simple C++ console application is recommended.
    • A new window will appear where the project name, location, and solution name can be defined.
    • The solution is a group of projects. Large applications can be divided into smaller projects within the same solution to make them easier to maintain.
    • Visual Studio’s Solution Explorer displays the solution name and the projects inside it. If the Solution Explorer is not visible, it can be opened by going to View and selecting Solution Explorer.
    • When a project is created, default folders and files are created. Source code files are placed in the source files folder.
    • The part of Visual Studio where you write code is a text editor with different colors to indicate the purpose or role of the code.
    • To run code, you can click the green play button.
    • It automatically builds code when started from Visual Studio.

    C++ Data Types: Variables, Storage, and Overflow

    Here’s what the sources say about data types:

    • A variable is a container for a certain data type. You can put a whole number, character, decimal point number, or a Boolean value inside it.
    • In C++, you cannot put two different data types inside one variable. It is also not possible to change a data type of variables once it is created.
    • Here are some of the most basic data types in C++:
    • int: can hold negative whole numbers, zero, and positive whole numbers.
    • char: can store one character.
    • bool: can store a true or false value.
    • float: can store decimal point numbers.
    • double: can also store decimal numbers, but it can hold much more data than a float. Double is double the size of float. Float takes four bytes, while double takes eight.
    • unsigned int: If you want to use only positive integer numbers, there is a data type for that called unsigned int. Its size is the same as of int (four bytes or 32 bits). However, since it is unsigned, it does not use one bit for sign because the sign is by default plus. It uses all 32 bits to represent value and those values go from zero to 4 billion and something.
    • Each data type takes a certain space in memory. To determine how much memory each takes, you can use the sizeof operator.
    • bool uses one byte.
    • char uses one byte.
    • float uses four bytes.
    • double uses eight bytes.
    • Each data type also has a maximum amount of data that they can hold. If you put too much data inside a variable, it is going to overflow. This is called data type overflow.
    • The int data type has reserved words for the minimum and maximum amounts.
    • int_min is the minimal amount for int in C++.
    • int_max is the maximum amount for int in C++.
    • The unsigned int data type also has a reserved word for the maximum amount.
    • uint_max
    • If you divide two whole numbers, the result will also be represented as a whole number. If you want to show the real result, you have to make one of them a float or double.
    • The modulo operator gives you the remainder of dividing two whole numbers.

    Conditional Logic: Mastering If/Else Statements

    Here’s what the sources say about the “if/else” statement:

    • The if statement is used when a block of code should be executed conditionally. This means the code will execute only in a certain situation.
    • An else block can be added, which will be executed if the initial if block is not executed.

    An example task is to check if a number entered by a user is even or odd and write that out to the user.

    Here’s how the “if/else” statement would be structured in code for this task:

    1. Prompt the user to enter a whole number.
    2. Use cin command to store the user’s input as an integer in a variable called number.
    3. Use the modulo operator to determine whether the number the user entered is even or odd. The modulo operator gives the remainder of dividing two whole numbers.
    4. Use the if statement to check whether the number modulo 2 is equal to 0. The == operator is used to check equality.
    5. If the result is zero, the program should output to the user that the number is even.
    6. If the result is not zero, the else statement is used to output to the user that the number is odd.

    #include <iostream>

    using namespace std;

    int main() {

    int number;

    cout << “Please enter whole number” << endl;

    cin >> number;

    if (number % 2 == 0) {

    cout << “You have entered even number” << endl;

    } else {

    cout << “You have entered odd number” << endl;

    }

    cout << “Thanks bye” << endl;

    }

    Complex “if/else” Statements

    • “If/else” statements can be more complex.
    • If you are not familiar with “if/else” statements, it is recommended to first watch a video explaining the basics before moving on to the more complex uses.

    Consider a task where the user enters the lengths of a triangle’s sides (a, b, and c), and the program determines whether the triangle is equilateral, isosceles, or scalene:

    • An equilateral triangle has all three sides of the same length.
    • An isosceles triangle has two sides of the same length.
    • A scalene triangle has all three sides of different lengths.

    Here’s how the “if/else” statement could be structured in code for this task:

    1. Declare three float variables: a, b, and c.
    2. Prompt the user to enter the side lengths of the triangle.
    3. Use cin command to store the user’s input in the variables a, b, and c.
    4. Use an if statement to check if a is equal to b AND b is equal to c. The && operator is a logical end operator. The expression will be true only if both sides are true.
    5. If the result is true, output to the user that the triangle is equilateral.
    6. If the result is false, use an else statement and nest another if/else statement.
    7. Check if a is not equal to b AND a is not equal to c AND b is not equal to c. The != operator means “not equal to”.
    8. If the result is true, output to the user that the triangle is scalene.
    9. If the result is false, output to the user that the triangle is isosceles.

    #include <iostream>

    using namespace std;

    int main() {

    float a, b, c;

    cout << “Please enter a, b, and c” << endl;

    cin >> a >> b >> c;

    if (a == b && b == c) {

    cout << “equilateral triangle” << endl;

    } else {

    if (a != b && a != c && b != c) {

    cout << “scalene triangle” << endl;

    } else {

    cout << “isosceles triangle” << endl;

    }

    }

    }

    Understanding Loop Control Structures: For, While, and Do While

    Here’s what the sources say about loop control:

    • There are three types of loops: for loop, while loop, and do while loop.
    • for loop: Before the loop starts, you should know how many iterations that loop is going to make.
    • The syntax of the for loop is for (initial value of counter; condition; increment/decrement).
    • Inside the parentheses, you put three expressions:
    • Set the initial value of the counter variable.
    • Put the condition that your for loop is going to check each time that it wants to run a block of code. Before each iteration, it is going to check that condition.
    • A way for your counter value to come to that condition. You have to either increase or decrease your counter variable in order to reach that condition at a certain point, and then when that condition results as false, your for loop is not going to be executed anymore.
    • After the for loop parentheses, you put curly brackets in which you write out the code that is going to be executed in each iteration of your for loop.
    • while loop: With a while loop, you first check the condition, and then if that condition results as true, you can really proceed with executing your block of code that comes after your while.
    • do while loop: With a do while loop, you first execute a block of code and then check the condition. If the condition results as true, you go back and do one more iteration.
    • The syntax of the do while loop is do {code block} while (condition);.
    • The code inside the do block is executed at least once, regardless of whether the condition is true or false.

    Here’s an example of using the do while loop:

    int pin, usersPin, errorCounter = 0;

    do {

    cout << “Pin: ” << endl;

    cin >> pin;

    if (pin != usersPin) {

    errorCounter++;

    }

    } while (errorCounter < 3 && pin != usersPin);

    • break statement: The break keyword is used so that your switch case statement knows where your first case ends.
    • If you don’t put the break statement, you are going to get your program to behave unexpectedly.
    • When the program reaches the break keyword, the loop will stop.

    Nested Loops

    • Loops can be nested, meaning you can put a loop inside another loop.
    • An example of using nested loops is drawing a rectangle shape.
    • The outer loop controls the height of the rectangle.
    • The inner loop controls the width of the rectangle.

    C++ Function Guide: Creation, Parameters, and Overloading

    Here’s what the sources say about function creation:

    • A function is a block of code that is grouped together and performs a specific task. The code in the function is executed only when the function is called or invoked.
    • Every C++ program contains at least one function, the main function. The execution of the program begins on the first line of the main function and ends on the last line, or when a return statement is encountered.
    • Besides the main function, you can create your own functions.
    • Functions make your code reusable. You can write code to solve a problem once, put the code in a function, and then call the function many times.
    • Each function should perform a specific task. This makes the code easier to manage.

    How to create a function:

    1. Specify the return type of the function. If the function does not return a value, use the void return type.
    2. Write the name of the function.
    3. In parentheses, list any arguments or parameters that the function receives. The parentheses can be left empty if the function does not receive any arguments.
    4. In curly brackets, write the body of the function. This is the code that will be executed when the function is called.

    Here is an example:

    void function() {

    std::cout << “hello from function” << std::endl;

    }

    Function Declaration and Definition

    • The recommended way to create functions is to separate the declaration and the definition.
    • The declaration of a function tells the compiler the return type, name, and parameters of the function. The function declaration goes before the main function.
    • The definition of a function is the actual code that will be executed when the function is called. The definition goes after the main function.
    • To navigate to a function’s definition, right-click the name of the function and select “go to definition,” or press F12.

    Here is an example:

    #include <iostream>

    //Function declaration

    void myFunction();

    int main() {

    myFunction();

    return 0;

    }

    //Function definition

    void myFunction() {

    std::cout << “Function was executed!” << std::endl;

    }

    Function Parameters

    • Parameters are values that are passed to a function. Sometimes a function needs to receive a certain value or variable in order to perform a task.
    • To create a function that receives a parameter, specify the type and name of the parameter in the function’s parentheses.

    Here is an example:

    void introduceMe(std::string name)

    {

    std::cout << “My name is ” << name << std::endl;

    }

    • To pass multiple arguments to a function, use a comma to separate the arguments in the function’s parentheses.

    Here is an example:

    void introduceMe(std::string name, std::string city, int age)

    {

    std::cout << “My name is ” << name << std::endl;

    std::cout << “I am from ” << city << std::endl;

    std::cout << “I am ” << age << ” years old” <<std::endl;

    }

    • A default parameter is a parameter that has a default value. If a value is not passed for that parameter when the function is called, the default value will be used. To specify a default parameter, assign a value to the parameter in the function definition.

    Here is an example:

    void introduceMe(std::string name, std::string city, int age=0)

    {

    std::cout << “My name is ” << name << std::endl;

    std::cout << “I am from ” << city << std::endl;

    if (age != 0){

    std::cout << “I am ” << age << ” years old” <<std::endl;

    }

    }

    • Default arguments can only be specified at the end of the parameter list.

    Function Return Statements

    • The return type of a function can be any data type, including int, float, bool, char, or double. It can also be void, which means that the function does not return anything.
    • A function can return only one value. Only one return statement inside a function will be executed.
    • Not all functions need to return a value. An example of a function that does not return a value is a function that writes a menu to the user.
    • Functions that return a value can perform a calculation on arguments passed to the function and then return the result of that calculation.

    Function Overloading

    • Function overloading means that you can create multiple functions with the same name, but with different parameters.
    • When functions do the same thing but use different data types, you can use the same name as long as the parameters are different.
    • When a function is called, the compiler decides which function to call based on the data types of the arguments that are passed to it.
    C++ FULL COURSE For Beginners (Learn C++ in 10 hours)

    The Original Text

    hi everyone welcome to my channel my name is Salina I am a software engineer and I make programming and it related videos here on YouTube so if that is something that is of interest to you consider subscribing to my channel and this video is going to be allinone C++ full course for beginners and the goal of this video is to take you from that place where you are struggling with programming where you don’t understand how to read code or write code to a place where where you feel really comfortable writing code and reading code and you really understand what the code is doing because that is the most important part so this course consists of lectures where I will teach you a specific concept and then uh there will be a task and by solving that task you will get a good understanding of that specific concept and then the complexity of those tasks will gradually increase so that at the end of this video If you finish it you will have have a very good understanding of the most important programming Concepts not only in C++ but you will be able to take that knowledge with you to other programming languages as well and then uh at the end after you finish this course in the description I will leave directions for you on what should be your next step because I have created a road map with steps and directions so that if you follow those you will be able to build your programming knowledge to a very very high level but before we start I want to ask you one question and I feel extremely proud and happy that you decided to invest your time to learn programming and I can personally give you many reasons why that is a great decision but what I’m more interested in is what are your reasons why would you like to learn programming and be good at it is it because you are very creative person or you want to get a job and earn a lot of money or you want to gain those problem solving skills or because you think that programming is cool um so any other reason that you might have as well please write that in the comments down below and then uh make a public commitment before you start because that is something that will motivate you so um write I will learn programming because and then put your reason and hold yourself accountable so I am very much looking forward to reading your answer in the comments down below so without further Ado I will just roll the intro and let’s start with the [Music] video hi guys very warm welcome to everyone watching this video and this video is going to be introduction to C++ programming language and the first video of this course I was planning on dividing this video into two separate parts so that in the first part I’m going to explain some basic concepts some general concepts that are related to C++ and that you need to understand in my opinion first before starting to write code and then in the second part we are going to build our first C++ program so I’m going to include in the description of this video a time stamp so that you can navigate yourself to the coding part if you want but if you’re an absolute beginner I would recommend you to watch the entire video Let’s explain a couple of Concepts before we actually start to write codes so that you are familiar with them you may wonder what kind of applications you can build with C++ well C++ is general purpose language that means that it can be used to build all type of applications so uh it is very close to the hardware and that means that it can manipulate resources easily so you can build operating systems if you want with it you can build compilers browsers uh demanding games so all general purpose software can be built with C++ uh it is not specific for only one domain but it can be used to solve and build different types of applications uh after that I would like to mention that C++ is compiled language that means that the code that you write first has to be compiled or uh converted translated into another language that is understandable to your machine to your computer so that phase is called compiling code or building code there are certain errors that can occur in this phase of course and those are compile time errors uh this type of Errors is usually the most common among beginners among people who are just starting to learn C++ and we are going to demonstrate some of those compile time errors when we start uh coding after that C++ is case sensitive language that means that uh C++ distinguishes between lowercase and uppercase letters so if you have for example a variable all up uppercase and then a variable all lowercase so the same meaning the same word those two are going to be treated and and understood differently as different variables uh by C++ so it is case sensitive language why C++ was created another question because before it there were other programming languages uh well yes they were uh and it was created in 1980s uh and it was created with two programming languages in mind one of those two was simula uh and the other one was C so simula at the time was great language for human way of understanding and representing things so it was very understandable and easy to use to humans but at the same time it was very very slow so uh they decided to combine it with another programming language a fast one and at that time the best choice for that was C programming language so they combined did the two and they got C++ uh C++ is very very uh understandable language very easy to use by humans so you can build and maintain uh huge projects with C++ uh but at the same time because of this C part uh it is uh very close to the hardware so uh demanding tasks can be executed fast uh and also well since since it was created uh from C programming language you can say that any valid uh C program is actually valid C++ program so if you’ve ever built a c program you have actually built a C++ program already as I have already said the code that you write is not directly understandable to your machine so first it has to be converted into another language that is understandable to your computer but the one the language that is understandable to you is called source code I am going to put here an example of source code uh and I’m also one wondering at this moment what do you think that this code does so before we started any programming any coding at all what do you think that the result of this program is going to be so just to check how understandable C++ really is even for someone who has not have a lot of experience in coding so write in the comments of the video what you think that this code is going to do and I’m going to check those so at the same time you’re going to be doing uh something called writing pseudo code which means describing what a program does but just in plain English so no C++ so this is uh the source code after that that source code is transferred or uh translated into another form another language which is understandable to your computer and that is object code that object code is usually in the form of binary numbers so ones and zeros and that is the only language that your computer actually understand and this is an example of your uh machine language I’m also not going to ask anyone to describe what this here does because this is highly unreadable and cannot be understood by humans but uh as I said it is the only language that your machine understands so algorithm what is algorithm algorithm is nothing more than a recipe so steps instructions that you write to your computer list of ingredients and and steps that your computer needs to do in order to perform a certain task that’s algorithm now that we have understood these Concepts let’s switch to more practical part so the tool that we are going to use is called Visual Studio 2019 and there is a lot of tutorials on YouTube on how you can download and install the visual studio and you can also use Community version for free so uh when we open Visual Studio you can see that here in this left part we have our recent projects uh so the project that that I have recently created and this may be empty if you haven’t used your visual studio so on the other side there is a menu with multiple options you have uh the option to check out your code from GitHub here you can open existing project from your computer uh and continue working on that but the option that we are going to use is called create new project so we are going to click that so this new window now here appears and we are going to Define what kind of project we want as beginners we are going to build a very simple app so we are going to build a C++ console application so you can type in a C++ and make sure to select C++ console application so not c not Visual Basic but C++ and when you clicked it you can now uh click uh when you selected it you can now click next so this new window uh now we get a new window uh where we have to Define our project name location where our project is going to be saved and and our solution name as default our solution is named the same as our project what solution is is just actually a group of project so if you had a huge application and you wanted to divide it in smaller parts so that it is easier to maintain you could divide it in multiple projects but all of those projects would be part of the same solution so as we are since we are building a simple app we have only one project and we will name it my first app so my my first app and location for our project we can either enter manually or we can do it by clicking this button here and I want my f files to be saved on desktop so I’m going to select uh desktop and now we are done with uh with creating our project so uh with configuring our project so we can click uh create so the tool that we are going to use uh Visual Studio is an IDE or integrated development environment that means that it has a lot more options than just those that we as beginners are going to need and use so for now I’m going to explain only the most basic ones the ones that we are going to need as beginners but as we progress along the way I’m going to explain the new features that we’ll use so so the first thing that you can see here is our solution Explorer so uh if you cannot see your solution Explorer you can click here to this View and select solution Explorer and that should bring your solution Explorer back to view so as we said our solution Explorer is named my first app and it has one project inside it so this this this project is this one here and as you can see when we created our project it was created with some default folders and files for now we are going to use only one file so you can delete these folders header files and resource files if you want just click right click and click delete so now this source files folder is where we are going to put our source code files if you remember from before I have said that uh source code is the code that we write and that is understandable to us so this is our source code file so this with CPP extension so when we created our project this file was created by default and if you double click it it opens uh here so this part here is nothing more than a than a text editor really as any text editor it just has these uh different colors depending on the purpose or the role of the code so that you can manage the code easier if it were all the same color it would be harder to uh to read so for example this green part here is a comment comment is just a note for yourself so compiler will not try to translate commented lines so if if you type for example here this slash slash or that means actually begin comment and then you can explain for example what this preceding code does so you can write this will output to the console hello world so this will output to the console hello world so that when you for example come tomorrow to this code and you have forgotten what this code here does this will remind you this comment here and these are some default comments which I will delete now we are not going to uh need this so just select everything and click delete as you would in any regular text editor this part here also now let’s explain what we got here so this include iio stream is actually a header file so it is also called a library and this um I stream is input output Stream So it allows our uh us to input and output data to and from our program for example thanks to this we can use commands such as this here so see out or console output so without having this we would actually have to program ourselves how we will input and output data in uh our in our console so we will not delete this line here now check this code here it says main well that means that this is our main function so a main procedure that our program is going to execute so whenever whatever you put actually in uh these braces here your program will execute and the execution of your program begins here and it ends here so since this here is the the scope of your main function so you can collapse it by clicking here and you see that everything is collapsed now so for now it’s enough for you to know that this is our main method our main procedure and later in this course we are going to uh learn and understand what methods are used for what is their purpose and we are also going to create a lot of Our Own methods so now we have this uh C out or console output which is the command to Output to the console and then we have also combined with this um STD and these redirection signs so STD is the Nam space for this C out so that’s how your computer knows what this SE out really is I will show you later how you can get rid of this if you really want and we also have this hello world in uh quotation marks okay let’s see what we have learned so far we said that this is our solution it inside it has one project and within that project we have this file with uh with extension. CPP which is our source code so if we double click this file it brings us here so to this text editor and this is our program this is the code of our program now how we can run this code well see this green play button here well that’s our start button it’s really uh it’s really intuitive so if I click it we will get our hello world text here which I have outputed to the console uh and you can also see that we we have besides our hello world we have gotten some junk text here so what I’m going to do is show you how you can get rid of this in a moment so let’s close our program for a moment and what you need to do in order to get rid of this junk text is type this command here so system pause greater than zero in quotation mark and the end of command you notice that at each of uh at the end of each command uh you have to put this semic column and if you didn’t it would result in an compiler error and I will demonstrate that let’s run our program now and you will see that our junk text has disappeared so as I said after each command you have to put this semic column and if you if you didn’t do that it would create a syntatic error and that then your your compiler would not be able to understand and your program would not run actually your program would not start so if I delete this semicolon here you see that something has changed in this in this window here so you see this R error error red sign um well if I hover over it you see you see it here also here here uh it says expected a semicolon which is very clearly says that you are missing a semicolon and if you see this red underline here it says also expected a semic colum so uh before this you are missing a semic column here so if I add it here if I add it here our error will disappear so if you try to run your program before fixing this error it would prompt you with with a window like this so it says you have one failed project and zero succeeded projects so this is the code building that I have mentioned before so this one project which is actually the only project that we have has failed building so your compiler does not actually understand what you have written since you are missing a semi uh column so another thing how you could know that you have syntax error uh except from this uh this prompt window that we got is this uh syntax error so missing semic column before this closed brace and if you click it here it will take you right where you need to go to fix your error so it’s it’s very useful and if I press my play button again it now says hello world so I will stop program now uh you can do it either by clicking this red sign here which says stop debugging or you can click this X on the console window so if some other error has happened to you which didn’t happen to me here you can write that in the comments down below and I will gladly help you also someone else can help you from uh from the other people learning from this video and I would highly encourage that since in my opinion the best way to learn something is to try to reproduce what you’ve learned and to explain it to someone else so write in the comments if you got some other error now let’s see how we can upgrade our program so let’s write something else let’s add for example STD two column signs console out so uh under quotation marks I will put something that I want to write out so let’s say for example my name is Salina you can put your name of course and at the end of each command you put semicolon and let’s add one more so let’s say today is Friday and also add end of command here so it should write when we run our program it should write these sentences in uh this order here so you can run your program and if you can notice it has this new line in the first sentence so this is because of this this back slash n so that puts whatever text is coming after in a new line so you can put uh that text in a new line by either entering a back sln or with adding this STD end line so STD end line and I have previously stopped my program if I run it again you see that that we have gotten a new line here you see also that this um STD here is becoming a bit tedious to write again and again and I’ve told you that I’m going to show you how you can get rid of this uh so what you can do is you can uh put this STD on a global level so you can say using using namespace STD using namespace STD and what will that do is reference this STD namespace on a global level so you don’t have to uh reference it every time that you are using it and now we can delete all of these so wherever you have written STD that’s going to be referenced here now and you don’t need it need to write it separately and if we run our program uh here we are going to get uh our result so we have also uh this new line added by either sln or this end line here okay so in this video we have learned how we can output data in a console and in the next video we are going to see how we can input data into our uh console so we can ask user to input data and we are also going to talk about variables and data types another thing that I want to show you before I finish this video is you may be wondering okay do I have to start Visual Studio every time that I want to run my program is there any other way for me to to execute my program uh and uh the answer is no you don’t have to start Visual Studio every time there is another way to start your program for for w from Windows so let’s save all changes that we have made here so far so you can press control+ s or um if you have made any changes you see this star here so it is indicating indicating that you have unsaved changes so you can right click on that and click save and you see that that start disappears now so let’s find a folder where we have created our project for me that was desktop uh if you follow this tutorial from the beginning you created it also and if you follow me you created it also on desktop uh so you can open your folder you can uh go to debug and inside that you uh see this file here it says application so this is your program so uh if you right click on that and you check its properties you will see that it says exe that means that it is executable file so that is your program that is your um application and if you double click on that well you see that it runs same as in visual studio so you can start your program from Windows actually if you want to show it to your friends or someone else you don’t have to you don’t have to open Visual Studio each time that you want to uh to run your program but one more thing to keep in mind is that if I go to visual studio now and I add one more line let’s say let’s say we write out have a nice day so and and if I save it so contrl s and if I try to open my program from Windows now what you’ll see now is that this new line that I have just added is missing but why is that so you know well um if you remember when we were talking about building code we said that that’s the phase of uh converting source code that you have written into a code that your machine understands and when you start your code from Visual Studio it does that process automatically for you so it builds your code and then it executes your your program but when you are starting your uh program from uh Windows it is missing that phase of building code so your uh recent changes your last changes were not translated so your uh computer has only the only translated version that it has is the previous one so without about your uh recently added changes what you need to do is you either have to run uh your code from Visual Studio first or it’s enough for you just to build that code inside visual studio and what happens when you do that so just click here and you can click build and what happens is your Visual Studio translates this code that you have written and it saves it here and now when you run it and when your windows runs it it has uh the the latest version it has the latest changes so this is the small trick that I wanted to uh show you so uh this will be all for this video and uh if you came across to some errors that didn’t happen here to me or you have any questions you can write those in the comments and I will I will answer those and if you watched so far you can like this video you can subscribe and share it with someone else who would also like to learn programming and I will see you in the next video hi guys I hope you are all well and welcome to the second video of C++ for beginners in this video we are going to talk about variables data types and also I’m going to explain how you can enter data in your program and how that data is encoded into numbers using something called asky table so here I have opened visual studio and if you are not familiar with Visual Studio or there is some code that you see here but you don’t understand it I would recommend you to watch my first video of this course the link is going to be in the description of this video and then come back to this video so let’s talk about variables now what is variable well I like to explain it a real life example for example you see this glass here well what I can say about this glass is that it is a container for a certain type of liquid so it can hold water milk tea juice whatever you want really and the same way a variable is a container but for a certain data type so you can put whole number inside it you can put character or a decimal point number or a Boolean value meaning true or false value so they are the same in this aspect another thing that I can say about this glass is that it defines a maximum amount of liquid that it can hold so it has a max limit and if you put too much it will overflow the same way with variables variables also Define a maximum amount of data that they can hold for example if you have a whole number variable well there is a Max number limit for that variable that it can hold and also if you put too much it is going to overflow it is literally called data type overflow so it is a container the same as variable and also it defines a maximum amount of data that it can hold but how much data you really put inside that variable so the same way with with the water inside this glass if you decide to put 1/3 or 1/2 or 2/3 of this glass the same way is with variables you can put however much you want as long as you don’t put too much because then it’s going to overflow one thing that is different though between variables and this glass is that you can put one day inside this glass you can put water the next day you can put juice the next day you can put milk then tea or even you can mix two liquids but with variables you cannot do that at least not with Once in C Plus+ there are certain languages that you can do that with and there is also advantages and disadvantages when it comes to that but in C++ you cannot put two different data types inside one variables and you can also not change a data type of variables once you create it so let me show you what I’m talking about on a practical example let’s say that you want to create a variable that is going to hold your annual salary well that variable is definitely going to be a decimal point number or also floating Point number that’s how it’s called in C++ and the type that is used for that is called float so I’m going to say float and then I’m going to give a name to that variable since we said that is going to hold a annual salary we are going to call it annual salary okay and then we are going to assign it a value and that value is going to be let’s say 50,000 99 so now what I have done here is I have created a variable called annual salary I have said that that variable is going to be of type floating Point number and then I have put inside that variable 5099 so now let’s see how we can base on this variable based on our annual salary calculate how much our user is earning every month so what we are going to do is we are going to create another variable we are going to call it monthly salary and we are going to assign that variable a result of dividing this annual salary with 12 months so we are creating a variable of type float also since the result of division usually can be also floating Point number or decimal number and because of that we are using also float type for our monthly salary variable so I’m creating monthly salary variable and I’m going to say that that variable is going to hold result of this expression annual salary divided by 12 months and now we have result of this division inside this variable and what we are left to do is to write that result out to our user so I’m going to say see out since that’s the command that we use to Output data to console and I’m going to say your monthly salary is and I’m going to say monthly salary so one thing to notice here is that when you are writing out strings or when you’re writing out data like this you use quotation marks but when you want to write out the value that you are holding inside a variable well then you just put the name of your variable you don’t use any quotation marks then and now we can run our program and let’s see what’s the result that we got you see here your monthly salary is 4,166 75 so if you want to check that out you can uh you can calculate it in your calculator one thing that uh that bothers me in this program is that we have hardcoded this value here so we have hardcoded coded this 50,000 99 not every everyone’s salary is 50,9 and what if we wanted our user to enter what his salary is during the execution of our of our program so when he runs our program our program should ask him what is your annual salary and then he enters that salary and then we calculate his monthly salary based on the number that he has entered so I would like to upgrade this program now to work like I just explained and how we are going to do that well first I’m going to delete these 50,000 99 okay and then we are left with this situation here so it says float annual salary that means that I have just created a variable called annual salary and I have said I’m going to put a floating Point number inside that variable but I have not assigned any value to it yet so here we have a container for our annual salary and that container doesn’t hold any value and if we try to run our program now what do you think that we are going to get write that in the comments before I run this program and now I’m going to uh so pause the video and think about it and then write write your answer in the comments and now I’m going to run the the program and you can see that we have some build errors as this here uh this window here says so let’s see if we open this part here it says we have one error and that error is uninitialized local variable annual salary used what that means is that this exess expression here if you see this green underline It also says using uninitialized memory annual salary well that means that this expression here our computer doesn’t know how to do this expression since we haven’t assigned any value to our annual salary variable so it doesn’t know how to divide that that with 12 since there is no value inside that container inside that variable so this causes a compiler error and whoever has written that compiler error is going to occure he was right so how we have to what we have to do to correct this is we have to ask our user to enter his uh annual salary so what we are going to do now is let’s see First Command that we use to Output data from our program into our console is C out so console output and the command that we use to input data is console input or C in so I’m going to say C in and then we use these other redirection signs and then we say what is the variable that we want to store what our user has entered and I’m going to say annual salary so what I have said here is our user is going to console input the data and then whatever he has inputed you have to redirect that inside our annual salary variable so now if I run my program now you see that our program runs now so there is no compile time error and also our cursor is blinking well it is blinking because it expects here our user to enter annual salary but this is not really clear to someone who has not made this program so what we have to do if I enter some value now well it is going to calculate it correctly but this is not really user friendly so what we have to do is we have to write a message to our user before he enters anything so that he knows what he should enter so before this C in command I’m going to say C out and I’m going to say please enter your annual salary okay and now if I run my program you are going to see please enter your annual salary and the cursor is blinking waiting for you to enter the value and if I I say for example 40,000 you see that your monthly salary is 33333 so the program has calculated your monthly salary and the number is based on whatever our user decides to input so we have upgraded our program and there is also one more thing that I would like to show you when we are doing this example and that is let’s say that we want to calculate how much money our user is going to earn in 10 years so let’s say see out in 10 years you will earn and now we have to put a value of how much money he is going to earn and if you look at this situation here we first created our monthly salary variable and we then assigned it a value of annual salary divided by 12 but there is another way that we can write out results of Expressions without creating any variables if that is what we need and that is just here so in this line in 10 years you will earn you add these redirection signs and then you say expression that you want your computer to calculate and what we want to calculate is how how much our user is going to earn in 10 years so that is annual salary times 10 and if you do it this way so if you don’t decide to create a variable then you will not be able to use result of this expression later in your program so you don’t have a container that holds this 10 year salary but you have a container that holds annual salary and monthly salary so each time that you want to to write out or do something with your 10year salary you will have to write this expression while if you want to do something with your monthly salary you have a container that is holding that value directly for you and you can access it so if we run our program now you see it expects us to enter our annual salary let’s say 50,000 and you see here your monthly salary is 4,166 67 and then in 10 years you will earn what is this half a million so okay one thing that we are missing here then and that you can add is end line or back slash end so you can add it here and your program is going to format your text nicely so this line should go here like this if I if I add here one more end line and if I run my program again you see enter 50,000 and now we have our text formatted nicely because of this end line that I have just added let’s now create another variable and this time we are going to create a variable of type character so Char that is the type that is used for character variables in C++ it’s called Char and let’s name our variable character and when you want to assign a value to a character variable in C++ what you use is these single quotes like this if you see this example here when we are writing out text so string of text we use these double quotation marks but when we want to assign a character value of a character variable we use these single quotations like here and there are also some more rules when it comes to naming your variables and the most important one in my opinion and the most important one to make it easier to you is to name your variables according to their purpose so give meaningful names to your variables that is really really important for example you see this uh monthly salary variable here we could have as well named this variable blah blah blah and copy it here also because we are having compiler error right now because our compiler does not know what this variable really is you see it says identifier is undefined because you have not created this variable here because it supposes that it is a variable but it has not been created before so it does not recognize what this variable is so we have to copy the new name here also and now our compile time error disappears and this here this name does not represent anything to your computer so your computer is now going to run your program and your program is going to work just the same as it did before but this is really making it hard for you to understand what your code is doing and especially if you come to this for example in 10 days or someone else tries to understand your PR program this is really hard to read and he will just try to uncover really what your program is doing without understanding it because you have used these blah blah blah names for your variables the same situation would be if you for example have three boxes inside your kitchen and you you use one for storing sugar and flour and salt and instead of naming those sugar flour salt respectively you decide to name them Red Box green box and blue box and then in someone else comes to your house someone else comes to your program he does not really know where to find sugar because red does not mean that that box is storing sugar so you should name that box sugar box because imagine have three is easily easy to remember but imagine having 10 boxes or 10 variables or a hundred of them or even a thousand which is very common inside large programs so what you should do and I am going to do is return that previous name so monthly salary and here also so you should give meaningful names to your variables that is very important and that is the first rule the second rule is that well the second and third and the fourth are the rules that you will have to obey in most cases because if you don’t then you are just going to get a compile time error in 99% of the cases let’s say and I’m not going to say what that 1% is because I want you to obey these rules so when it comes naming your variables another thing is that your variable names cannot contain any special characters except underscore so like this this here is valid name to your variable but if you try for example to name your your variable like this so you say plus character you see that here in this error window it says expected an identifier so you cannot use this to name your variable or this you cannot say character with this minus inside it so character minus um so these signs these special signs are used for something else they are operators inside C++ and and you are not supposed to use those inside your variable names if you really want to use some special signs what you should and can use is underscore like this so this is the only sign that is allowed and that I recommend for you to use for naming your variables that’s the second rule the third rule is that your variable names cannot begin with numbers like this so you cannot say eight character for example It also says expected an identifier but what you can do is you can say for example character 8 that is a valid name so a number can be on any other position except on the first position so this is a valid name for a variable so you can put also number here so you can say for example C12 eror 8 but again what does that really mean me that is not a meaningful name for a variable so again we come to the first rule so you should name your variables according to their purpose so I’m going to return this to character name again and then we have our third rule I guess which is you cannot use space inside your variable names so for example this this is not valid and your compiler says it here so it gives you an error it does not know what this really is so you cannot use Space Blank spaces inside your variable names because you are going to get compile time error and if I try to do that and I try to run my program I get the window so it says you cannot run this program you have syntatic errors what you should do is you should correct those errors and then you can really run your program like this this okay so let’s repeat these rules one more time the first rule is that you should give meaningful names to your variables so name them according to their purpose the second rule is that your variables cannot contain any special characters except underscore the third rule is that your variables cannot start with numbers you can put number on any other position but not on the first one and third rule is that and the fourth rule actually is that your variables cannot contain blank spaces so empty spaces no no in a variable name what you should do is you should name your variables according to their purpose so meaningfully and you should also use something called camel casing what is camel casing you see how I have named this annual salary here you see that the first letter of my variable name is small letter and then the next word starts with capital letter and that is called camel casing so for example you would name your variable like this first second third so like this you see that this first second third these are words inside your variable name and this F is lowercase letter that’s the start letter of your variable and then each next word begins with capital letter and all the rest is lowercase letters that is called camel casing and that is something that is usually used with C++ let’s talk about data types now I am going to delete this code so if you need this code for a bit longer you can pause the video here so what kind of data can we store in our variables Well for now we are going to cover only the most basic ones the ones that we are going to use frequently and you should know that there are a a lot more data types besides from these that we are going to mention here a more complex ones that we are going to cover later in these videos in this tutorial so the first one that I would like to mention is a whole number data type so integer a data type that can hold negative whole numbers zero and positive whole numbers so the type that is used for that and C++ is called int and good example example for INT variable is let’s say year of birth so that is an example of a whole number variable and let’s say that that variable is going to hold 1995 okay so that would be an integer variable after that we have already seen this so it is a character variable so let’s say Char and an example of a Char variable could be gender for example let’s call it gender and you can store f for female or M for male for example so the Char variable can store one character then the next one is Boolean value meaning true or false value this is the simplest one and the type that is used to store bullion is called bull and a good example for a bull value could be for example if you want to hold in your program a variable that tells you whether your user is older or younger than 18 years 18 years old so let’s call our variable is older than 18 and we can assign to that variable either value of true or false so I’m going to put true true here another very able another data type is decimal point number also called floating Point number which we have mentioned before and let’s create a variable of type float and let’s say that that variable is going to to hold our average grade so average grade and uh this average grade can also be a whole number but since it has potential to be also floating Point number or a decimal point number we are going to to use a float data type for this average grade and another data type that I would like to mention for also storing decimal numbers is called double and the difference between double and Float is that double is double size of float so if you remember when we talked previously about uh Tak memory space that that varibles take so float is taking four bytes and double is taking double of that so eight bytes so you can put much more data inside your double data type than inside float and let’s say for example that if you had a credit card and you had a lot of money a lot a lot a lot of money and you want to store that value inside a variable you would use a double data type so let’s say double balance if equals to this large number here which I’m not going to even try to read okay so these are the most common data types that we are going to use in this tutorial I have said earlier that each data type takes a certain space in memory but let’s see exactly how much each of these take for that we are going to use something called size of operator and let’s see how we use it so C out size of int is and then we write this size off so size of and in parenthesis we pass to it data type that we want to check how much memory it is using so int and if I run my program now you see that it says that int takes four bytes of memory and if you’ve ever actually studied binary algebra you would know that four bytes of memory is actually 32 bits since each bite has eight bits and as we said our int can store both positive and negative numbers and zero also remember that so the first of these 30 two bits is used to determine whether the number has plus sign or minus sign so whether it’s a positive or A negative number and then remaining 31 bits are used for this value itself so let’s check what is min value for our int let’s write that out let’s write C out int Min value is and we have reserved word for minimal amount for INT in C++ and that is intore min and if I run my program now you see that it says this minus 2 billion extremely hard to read this number but you see that this is the minimal amount of int so this number is actually 2 to ^ of 31 let’s just quickly write these so -1 -2 -3 and then minus this number here so this number as I said is 2 to the power of 31 why not 32 because this one bite is used to represent this minus prefix now we should check a positive number range so we also can write write int max value is and then there is another keyword in C++ for INT Max which is intore Max and are you expecting to see this same interval but just with plus sign so write in the comments what are you expecting to see and if I run my program you see that that did not happen and if some of you know why it did not happen I would also like to to hear what you think why we have this number here and then this number here for our negative and for our positive range so different ending number and I’m going to explain why because this positive range here we have to include zero also so in order to include one number here just let’s just copy this and paste it so our positive range is going to from one up to let’s say that it is this number but since it is including zero also in order to include one number here so zero you have to take one number here so this here is not eight anymore but is seven so that is why we got let’s say different number for our positive and negative range because this here includes zero also one thing that I have to mention though is that if you want to use only positive integer numbers there is a data type for that as well and data type that is used for that is called unsigned int and its size is the same as of int so four bytes or 32 bits but since it is unsigned that means that it does not use one bit for sign because the sign is by default plus but it uses all 32 bits to represent value and those values go from zero to let’s see exactly how big of a number 4 billion and something so see out size of unsigned int is and let’s see size of unsigned int this is the data type and let’s also write out what is the max value of unsigned int so let’s say C out u in max value is and there is there is also reserved War for that and that is U inore Max so if I run my program now you see that we got 4 billion and something number so double the size of this and this is actually 2 to ^ of 32 but minus one because we are also including zero in this range so let’s check these remaining data types I’m going to write those out quickly and I will be back so I have written here the rest of these data types and as you can see since our bull is only true or false value one bite is enough for bull our Char is using also one bite float is using four bytes double is using eight and I’m also going to include a table with some more data types which we haven’t mentioned here so if you need to check those out please pause the video one thing that I promis to show you is data type overflow let’s see what that is so let’s create a variable of type int and call it int Max and let’s say that I want to store inside that variable maximum amount of int So intore Max and I’m going to write that variable out now just see how big of value that really is so see out int Max and if I run my program now you see that I have gotten here this 2 billion very large number actually so that is the max amount of int now my question for you is what is going to happen in this situation so see out int Max + one what is going to be the result of our program now if I run it so some of you may know this already some of you may not but I am very interested in reading your answers so make sure to write your answers before watching my explanation on this write those in the comments down below and if I run my program now well our number has not increased by one but it has went to the minimal amount of int and why has that happened well that is the data type overflow that I was talking about and how this works actually is it works the same as your clock works so it goes 9 10 11 12 and then from 12 since that is the max value on your clock it does not go to 13 but it goes back to Min so 1 12 and then 1 and that is applicable here it went from the max value to Min value just by adding one and that is called data type overflow I already can see that this video is pretty pretty long and I’m currently having problems uploading very long videos to YouTube so I’m going to leave for the next video explanation of asky table and we are also going to do some more examples and practice C++ some more so make sure to subscribe to my channel and also click the Bell icon so that you are first to be notified when I upload my next video and also like it and share it with anyone who do you think could benefit from this video and I will see you in the next one hi guys welcome to my channel as I promised in my previous video in this video I’m going to explain the concept of asky table and then I’m going to give you an idea an example of a program that is very beginner friendly very simple but also very fun and that you can build only with knowledge from my two previous courses and this one so if you haven’t watched those make sure to watch them link is going to be somewhere here and also in the description and also make sure to like this video and to subscribe to my channel for more educational content and let’s begin now so what is aski well aski stands for American Standard code for information interchange and it was first created in order to standardize the way of representing characters in your computer so in asky table those characters are represented as numbers numeric codes and what this means is following let me give you an example when I first learned to read and write so when I was a little I decided to together with my friend create uh our special symbol language where we would exchange each character with a special symbol that only two of us could understand and then we would exchange letters us using that symbol language and no one else could understand those letters and also guys write in the comments down below if you did that I know you did so don’t make me feel like a weird one well that is exactly what your computer does it exchanges each character with a number so that it can understand it and it can communicate with other computers so this means that your computer or ask key table assigns to each character a unique number and let’s prove that now so how we can do that is in my visual studio I’m going to say see out and then in these parentheses I’m going to say int and then these single quotes and I’m going to say letter a and let’s add end line so this is one way of doing that and then there is another way of doing just the same thing and that is let’s say see out and then int and then inside these parentheses we are going to say our single quotes and our letter a and also add end line so this here is called casting operator and it is the operator that forces one data type to convert into another and since we said that each character has its numeric pair inside ask key table well we can ask our computer to give us that pair so here I’m seeing please tell me what is my numeric pair of my letter A so what number is my letter a and if I run my program now you see that I got 97 so our lowercase letter a is 9 97 in ask key table let’s check now a capital letter A so I’m going to say C out in off and let’s put our capital letter a and one more end line so if I run my program now you see that I’m going to get a different number so 65 and this is so that your computer can distinguish between lowercase and uppercase letters so ask key uses seven seven bits to represent each character and that means that it can represent 2 to the power of seven that’s how much characters it can represent so 128 characters and that is enough for all English characters so all English lowercase and up uppercase letters and numbers and also some special symbols but there is also a lot more languages and also languages that have a lot more characters so there is a lot more standards for representing those characters inside your computer so this that we have just mentioned is called um ask key and there is also extended ask key that is another standard that can represent more characters then there is also utf8 utf16 and a lot more different standards so what we should remember for now that is related to ask key is that as key represents each character with a number so it holds its numeric nuic match it’s num numeric pair in its table and then that we can also get get that numeric match using our casting operator so this here is a casting operator so now you may ask if we can get a numeric value of our letter so if if we can get our int number of our our letter can we do vice versa so can we get a character from our numeric value and the answer is yes we can convert a number into a letter also and I’m going to demonstrate how we can do that in a moment so you can say see out Char and let’s say Char of 65 and add end line and if I run my program you see that I’m going to get a letter A so capital letter a and now with this when you learn this you can get an idea on how you can build something more useful than than just basic hello world application so you can for example build a program that ciphers words and sentences in a s key and then also a program that deciphers those messages back into English readable characters so now we are going together to build a program that ciphers words into ask key codes and then I’m going to leave to you to build the program that deciphers those words back into English readable characters so let’s say that we want to Cipher a five letter word so what I’m going to do is what I need to do is to create five Char variables so I’m going to create five Char variables then I’m going to let my user input his letters inside those five chart variables and then I’m going to write out encoded words so I’m going to convert all of these letters in ask key codes and then I’m going to write that out to my user so I’m going to on a in a certain way Cipher his his word so I’m going to say here Char C1 Char C2 and then Char C3 and I won stop here for a moment I want to explain one thing when we first were talking about creating variables we said that this is the way of creating variables so you say the type of of your variable so Char in this case and then you say what name you are going to give to your V variable so in this case this is our C1 C2 C3 so this way of creating variables here it is correct but it is a bit tedious for this current situation there is another way of creating more than one variable and I’m going to demonstrate that now so what you can say also what you can do is Char C1 C2 C3 C4 and C5 and all separated with this comma sign so you can create more than one variable in one line like this but only if all of those variables are of the same type and in this situation they are so all of these variables are of type CH so I’ve now created five variables of type chart and another thing that I want to mention is that in upcoming videos we are going to learn how we can let our user decide how many characters how many uh how how many values he wants to enter during the execution of our program so now we have hardcoded these five values but we are going to learn more in the following courses and also another thing is that also in C++ there are a lot of solutions that you can use already made so that you can enter whole words or sentences so you don’t have to enter your word letter by letter so you don’t have to create variable for each letter that you want to enter but what I’m trying to explain here and what we want to understand here is how it really works in the background so how it works inside you have to understand that and I believe that that will give you a great advantage over those programmers that just know how to use something rather than how to make that something by themselves and then use it so I have here created five variables and each one hold a character that we will enter and let’s enter them now so what I’m going to say is C out enter five letters and then I’m going to say C in and I’m going going to put all my variables here so C1 C2 C3 C4 and C5 so if you can see here I have entered all of my five variables in a single line so you can do this you can buy B these operators like like this so that you can enter more than one variable in a single line the same way that you can bind your see out operator so that you can write out more than just one string so now what we are left to do is we have to write out our ask key message so what I’m going to say is see out ask key message and then I’m going to put int C1 let me write that out really quickly so I have written this message here and what I have said is console output asky message and then I have combined these C out operators so that I can write more than one variable in a single line so in a single command actually so I have said give me my int code of my C1 so give me my ask key code of my C1 variable and then put a blank space and then give me my asky code of my C2 and also C3 4 and five and I have also used these blank spaces because I don’t want to write just a single number in a single line because I want to know where my first character ends and where my second character begins that’s why I’m going to separate those codes with a empty space and also there’s another thing that I want to mention and it is that when you want to convert your variable so the value that you are holding in your variable and when you use your casting operator on that you don’t put your variable in a single quotation mark so you just put the name of your variable like this example here so if I run my program now you see that I get my message so enter five letters and I’m going to enter hello and you see now that I have this output asking message is 104 101 so 108 and 108 so that is our letter L you see that it has the same code and now I have gotten this asky message which is which is our ciphered word and also there is one thing that you that I want you to keep in mind and that is that this program here will not take into consideration your enter or your space key as a letter so if you if you put your enter or your space key however much times you want it will not treat it as a character there are some other functions that you can use in your C++ if you want to capture your enter for example or your space key such as cin.get if you really want you can Google that out but at this point we are keeping this very beginner friendly so this will not capture your enter and your space so let’s just prove that I’m I’m running my program once more and I’m going put enters and spaces and you see nothing is happening and then if I enter hello once more you see that I’m going to get the same numbers so the same message as before so we have built here a program that ciphers our words into s key and we have built this program after just studying a little bit of coding so imagine what you can do if you learned more so stay tuned make sure to subscribe to my channel and also like this video if you want to support me in filming these videos and also I’m going to leave to you to write a program that is going to decipher these messages from ask keyb into readable English words so you also can put your uh suggestions of a code in a comments down below and also what you can do you can upgrade this program here that we have written so that you can put in more words more sentences if you want and then you can put those coded encoded messages in the comments and everyone who wants to read those messages is going to have to build a program that is going to decipher those messages into readable English so subscribe to my channel like this video and I’ll see you in the next one hi guys welcome to my channel in today’s video I wanted to show you something that you are going to be using very often if you start on a programming path and that is if else statement so what is IFL statement well if statement is something that is used when you want to execute part of your code so block of your code conditionally which means not always but only in a certain situation and then if you add else block to that that else block is going to be executed otherwise so in the situation where your if block is not executed your else is going to be executed so let me explain that to you in a simple example here I have opened my visual studio and let’s quickly paste an exercise that we are going to do in this tutorial and that that is this task here so let’s say that our user has to enter a number a whole number integer number and then after that our program has to check whether that number is even or odd and has to write out that to our user so how we are going to solve this problem here well I’m going to explain explain this to you using diagrams because I believe that that is the best way for you to understand this if you haven’t used this IFL statement before and then what we are going to do after we understand those diagrams well we are literally going to just translate that diagram into our C++ code so let me open my tool here I have opened a tool that I’m going to be using for drawing diagrams it’s called blank diagram you can use whatever tool you want you can use even a paint or pen and paper if you want that will work as well so here I’m going to draw the flowchart of our program so how our program is going to be executed and let me add first here this shape and we are going to say that this is going to be the start of our program so I’m going to write out start and this indicates our main function let’s say the first line of our main function so here our program starts and then as we said in our task in our exercise our user has to enter an integer number and the shape that we are going to be using for that is this shape here so let me put this shape here and I’m going to write a text inside and I’m going to say in number so this shape here indicates that our user is going to enter some data in our program and why I’m using this shape because it looks like this it looks like a funnel so you can clearly visualize that something has to enter inside that shape so something has to be inputed in your program so I’m going to use this shape for that and then I’m going to say that our user has to enter an integer number which I’m going to call number so that variable I’m going to call number and let’s quickly add this Arrow so that we know that this is the flow of our program so after it has started our user enters a number and then after that what we have to do is our program has to decide whether that number that user has entered is even number or odd number so how we are going to do that well the shape that I’m going to be using for that decision let me find it Well it is this shape here so this diamond shape and as you can see it says decision on it so that’s the shape that we are going to be using and inside this this shape here I’m going to write a condition so as you can see our program flows this way and after it comes here as you can see it has one entry point and then it it can have multiple multiple flows that it can go to depending on this condition that we are going to put inside here but how we are going to decide whether that number that our user has entered is even or odd let me very quickly open my visual studio once more it is here and let me show you something I want to introduce you to a operator that is called modulo and that is used to show what is the remainder of dividing two whole numbers so I’m going to write out C out and then what I’m going to write out is let’s say 2 modulo 2 so this operator here gives you the remainder of dividing these two numbers and in this situation we are expecting to see a zero because 2 ided by 2 is 1 and then what remains after that operation is zero and that what remains should be should be shown when we use this operator here so if I run my program you can see that we have gotten the expected result so we have gotten zero here but let me show you what happens if I enter for example five well what we are going to get is one because 5 ided by two is going to be two and then that one that remains we can get using this operator and you see that it gives us the expected result so 5 modul 2 is equal to 1 so this operator here is what we are going to be using to determine whether our user has entered even number or odd number because when we get the result of modulating two numbers when our result is one that means that our user has has entered odd number and if we get zero as a result of this operation that means that our user has entered even number so I’m going to switch again to my diagram and then inside this decision here we are going to be writing we are going to write this condition here so I’m going to say number modulo 2 is equal to Zer so what this means it means that after our program has started and our user has entered the number that he wants an integer number we are coming to a decision point where we have to decide whether this number that he has entered after you modulate it with zero whether it’s a uh zero remainder or some other remainder so in this situation when this is zero we are going to execute a certain part of code and then let me add very quickly oh I’m impressed it already has this yes inside it and then we also have this no on this other line so in this situation where this results as operation that is true we are going to execute this part code of here so I’m going to add another shape which I cannot see but let me use this shape once more and I’m only going to rotate this shape like this and I’m going to delete this text and what we are going to be using this shape here for is to indicate that we are going to output something from our program so it looks like this which is clearly a visual of something is going to be outputed from it so it is just reverse of this shape here this funnel shape and then inside this shape let me write a text which is going to be um let’s say that in the case that this here results as a yes as a true operation so our number when it’s modulated by two it gives a zero remainder we are going to say that that number is even number so we are going to write that out to our user and then in the situation where this here results as a no so as operation that is false let me write out that here and I’m going to say to our user so I’m going to write out to my user that he has entered odd number and let’s just join this here like this okay so our user enters a number then we decide if that number modulated by two gives us zero and if yes we are going to write out to our user that that is a even number if no we are going to write out to our user that that number is odd number and this is here really our program what I’m going to add is let’s say that after this our program is going to stop so I’m going to to say here that this is the end of my program like this and let’s add one more stop of this flow here so in both of these situations after we have and after we have outputed to our user the result of this program our program is going to stop and this here really like these two stop points look a bit ugly to me so what I’m going to do instead of this I’m going to delete this you could have as well left it like this like like it was before but what I’m going to add I’m going to add one more of these diamond shapes only this time it’s going to be smaller and I’m going to say that in this situation it is going to be used only to say that this decision here this decision flow is going to be joined in this point here so like this I’m going to say whatever has happened whether this block of code or this block of code it has come to an end here and then after that from here I’m going to say now my program is going to stop like this and this and let me remove this yes and this is going to be the flowchart of our program so our program starts then our user enters integer number then we decide whether that number modulated by two is going to give us zero if yes we execute this else we execute this so if this is no and then we come to this which joins our two pads and then we can say that our program has ended and now let’s translate this to our code here I have opened both my visual studio and also I have exported this diagram so that we can translate it literally we can look at this diagram and then translate that into code so now I’m going to delete all of this that we have written inside our visual studio and I’m going to look at this picture and just translate it into C++ commands so the first this first shape here says that user is going to enter integer number inside our program and we are going to call that variable a number so I’m going to say int number and then this here this funnel shape really translates into C in command so user enter something inside our program and that is C in command and I’m going to say that user is going to enter a number before this I would like to add one more information to our user so that he knows what he should enter you could have as well put that to our diagram but I didn’t want it to make that diagram crowded so I didn’t but what we are going to add here is see out and then say please enter whole number like this so we write out a message to our user and after that our user as you can see here enters integer number we had also to declare this int number variable because you can enter the value only for variables that you have previously declared and then after that our program comes to this decision point and how we can represent this decision inside our code is using if statement so we are going to write here if and then I’m going to put this condition here inside these parentheses so I’m going to say if number modulo 2 equals zero this here is operator of equals so whether this side is equal to this side since only one of these so like this this operator here is used to assign value to a variable so that was already taken so this here two of these signs are used to check equality of these two sides so whether this is equal to this and then what I’m going to say as you can see from my diagram here we check this condition here and if this condition is true if this condition is yes we are going to execute a certain block of code and that is this code here and how you indicate a block of code in your C++ is using these braces here like this so this is your block of code that is going to to be executed in this yes situation and then in case that this no here happens so in case that this results as false you are going to execute another block of code and we represent that block of code using else statement so we are going to say if this here is true execute one block of code else if this here is false execute another block of code so here what our if makes us do well it says that we only have to write out to our user that he has entered even number because this shape here as you can see it looks like this and it represents that something should be outputed from your program so we are going to use for that our C out command so see out you have [Music] entered even number so like this and let’s add end line so in case that this here results as true we are going to Output to our user that he has entered even number else if this here results as false we are going to Output to our user let me copy this like this and we are going to change that only to odd so in case that this here results as false we are going to Output you have entered odd number so either this here is going to be executed or this here depending on this condition and you can see that from diag diagram clearly so when your program comes to this decision point it checks this condition and if the answer is true or yes it is going to execute this else if the answer is no it is going to execute this and then after that it really just joins these two flows and then that is the that is the stop point of your program so we can write here see out thanks by okay let’s say that that is the last line of our program you don’t I haven’t put this on on my diagram I okay so I’m going to run my program now and as you can see it says please enter a whole number so this line here and if I enter for example8 it is going to come to this line here and it is going to modulate our eight with two and if the result is zero which it is it is going to execute this line here and write out you have entered even number oh thanks we are missing an S here and then it writes out thanks by and let me add an S here okay and if I run my program again as you can see it ask me asks me again to enter a number and this time I’m going to enter five which we know that is an odd number it says you have entered an odd number because it has come to this decision Point here it has tried to modulate 5 with two and the result of that was not zero so it has not executed this but it has executed this else statement and it has written you have entered odd number as you can see here and then this thanks by okay so I hope that you have understood this and if you like me to use these diagrams to explain some more code that we are going to be using you can write that in the comments down below and I’m going to try to use more of these diagrams because I know that some people understand it better when there is a visual representation of your code I was one of those people when I first started learning programming so if you find it easier to understand when I use these diagrams I’m going to be using that so thanks for watching this video make sure to like it if you find it any helpful and also to subscribe to my channel and I’m going to see you in my next video bye hi guys welcome to my channel in this video I wanted to talk about if else statements but a bit more complex if El statements so that you can get an idea on how they are used in real life so if you’re not familiar with them at all like you have never heard of IFL statement then you should probably First Watch My First video of this subject and I’m going to link it somewhere here and then you can come back to this video but if you’re already familiar with the very basics of IFL statements then this video is right for you so that you can upgrade your knowledge so keep watching so the problem that we are going to solve in this video is the one that students usually get on their exams a lot and with the knowledge that you get from this video you are going to be able to recognize and solve other problems of this type and also if you don’t want to work with C++ this logic that I’m going to teach you today is going to be applicable in other programming languages as well so here’s the text of my problem and it says that our user should enter the lengths of a triangle so a b and c and after that our program should write out whether that triangle is equilateral isoceles or scaling triangle and as you already may know equilateral triangle is the one that has all three sides of the same length isoceles triangle has two sides of the same length and then scalene triangle is the one that has all three sides of different length so the way that we are going to solve this problem is we are going to really visualize the solution for this problem so that you can really understand it and that is going to be using diagrams the tool that I’m going to be using for drawing diagrams is called blank diagram you can use whatever tool you prefer even pen and paper if you want and the first shape that I’m going to put to this diagram is going to be this circle shape here let’s say that it is going to indicate the start position of our program so here is where our program starts and after our program has started what we want is we want our user to enter side lengths of our triangle and the shape that we are going to be using for DOT is this funnel shape here so that you can clearly visualize because of this funnel shape that something should enter inside it something should be inputed in your program and what should be inputed is side length so a b and c and the type that I’m going to be using for these three variables is float why float well because the lengths of sides of a triangle can be decimal point number or floating Point number so float and then let’s put this Arrow here so that you can oh so that you can uh visualize the flow of our program it goes like this and then after our user has inputed the side lengths what we should do is we should determine whether he has entered a equilateral triangle isoceles triangle or squalene triangle and what I’m going to do next is I’m going to use this diamond shape here which indicates decision in your program and what I’m going to put inside this shape here is condition the first thing that we want to check is whether whether our user has entered equilateral triangle so whether these three sides are all of the same length whether these three variables hold the same value and let me make this a bit bigger and inside here I’m going to say please check if my a is equal to my B and also if my B is equal to my C like this so let me join these two and I want to explain two things when it comes to this first one is this operator here this end operator these two ents this is logical end operator and it is used as I’m going to just explain so this expression here is going to result as true expression only in a situation where this here is true and also at the same time this here is true so in that case this whole expression expression is going to result as a true operation that is the logic behind this end operator and the second thing that I want to explain is following so I have said here please check if my a side length is equal to my B length and also if my b side length is equal to my C side length what you have Al what you can also put here is you can also say a because we have determined here that these two are of the same length so it really doesn’t matter if you put here A or B whichever you prefer so in this situation where this results as a true operation we are going this way and what I’m going to do when this results as a true operation as a yes operation I am going to use this shape here let me just rotate it I really don’t see a shape that that is this one so that’s why I’m using this reverse funnel shape and I’m rotating it so that you can clearly visualize something something that is being outputed from your program let me delete this text here and make it a bit wider and I’m going to put text inside it and what I want to write out in this situation here where this results as a true operation where this condition is fulfilled is that our user has entered equilateral triangle because all three sides are of the same length so let me write that out so in case that this condition condition here is true we are going to to write out our user that he has entered equilateral triangle and then let’s check the situation where this here results as a no operation so in that case we have to to determine whether our user has entered scaling triangle or a isoceles triangle and for that I’m going to be using another of these diamond shapes so another decision that we have to make and let’s put it here and oh no and the next thing that we want to check is following so I want check when I once I have determined that my user has not entered all three sides of the same length I want to determine whether he has entered all three sides of a different length so I’m going to put inside this shape here another condition and I’m going to say following so please check if my a is oops if my a is not equal to my B and also at the same time if my a is not equal to my C and also at the same time if my b is not equal to my C like this so this is the next condition that we want to check and this operator here is called not equal to operator and it is really reversed from this equal operator it has reversed logic so in this condition here what we want to check is whether my a side length is not equal to my bside length and also at the same time whether my aside length is not equal to my C side length and also whether my B is not equal to my C and if this here results as a true operation that means that all of these three side lengths are not equal they all have the different lengths so in that situation we are going to go this way and we are going to write out let me copy this shape and here I’m going to say please write out my user that he has entered a triangle that has all three different side lengths and that is going to be our scaling triangle like this okay so in the situation where this here results as a true operation it means that all of these three are of a different length and we write out to our user that he has entered scaling triangle and then the situation where this here results as a no because we have previously determined that these tree are definitely not of the same length and then we have in this condition here determined that these Tre are also not of a different length what is left is that the two of these two of these three sides are going to be of the same length and that is going to be the situation where we write out to our user well I can copy this and we write to our user that he has entered isoceles triangle so let me write that out okay so these three are three potential end points of our program so three potential solutions to our problem and after we write out to our user this or this or this I’m going to really put this one diamond shape just to indicate that our decision has now come to an end we have solved this problem and we are going to join these pads in this shape here so I’m going to put this and this like this so now after we have decided whether whether it’s an equilateral triangle or scaling or isoceles I can now say say you can resume the execution of my program normally so whatever I put after this shape here is going to be executed in either this case or this case or this case and what is going to be happening after the shape here is just stop so our program is going to stop but you can put a lot of code here if you need to so I’m going to say stop and let me delete this really I don’t need it okay let’s explain one more time this diagram so after our program start Parts our user should enter a b and c which represent side lengths of a triangle and I have used this float shape since since those side lines can be uh decimal point numbers and after our user has entered that we come to this decision Point here and what we want to decide here is first thing we want to check whether all of these three variables are of the same value so whether he has entered three same lengths for a triangle sides and in case that this here results as a true operation we are going this way and we write out to our user that he has entered equilateral triangle and after that we go this way and our program stops in the situation where this here results as a no operation we want to check something else so we are going this way and we come to another decision point and here we want to decide whether our user has entered a triangle that has all three three different side lengths so after we have checked that they are not equal we want to check whether all of three variables are of a different value and in case that this condition here results as a yes operation that means that he has entered scaling triangle but in case that this here results as a no operation we can now clearly say that he has entered isoceles triangle because we have checked here that these three sides are not the same and we have checked here that these three sides are not different so all of them are not difference and that means that two of them have to be equal and in that situation we go this way and we write out to our user that he has entered isoceles triangle and now we can go this way and you can see that in this situation as well our program stops here I have opened my flowchart and my visual studio so that we can just translate this diagram into our C++ code so the first thing here is our user enters our a b and c side length so let’s declare three variables of type float and let’s call them a b and c and now I’m just going to write out a message to my user so that he knows what he should enter so let’s say C out and please enter a and then B and then C like this and then let’s let’s use our C in command so that he enters his values okay let’s say first thing that our user uh enters is going to be stored inside my a variable after that what he enters please store that inside my B variable and then the third value that he enters is going to be stored inside my C variable so now that we have entered our side lengths of a triangle we come here so to a decision point and we said that we represent this with if else statement so I’m going to write here if and then inside these parentheses I’m going to say this condition here so please check like this please check if my a is equal to my B and then also check is my b equal to my C like this and if this this here this expression here results as true expression I’m going to execute one block of code and that block of codee is going to be this one here but if this expression here results as a false expression okay I am going to execute another block of code and that block of code we represent with our else statement like this okay and then let’s write this yes situation so let’s write here see out equilateral Al triangle so like this oops you should put that not in a quotation marks okay so in this situation where these three side lengths are equal we write out to our user that he has entered equilateral triangle but in the situation where this here results as false we have this else block to execute and let’s find out what is inside our else block so it is this code here and that is another if else statement so this if else statement statement is really nested inside this one here so it is nested inside this else block so here in these brackets here we are going to put another if El statement so let me write out if and then inside these parenthesis we put our condition from this decision here so from this diamond shape here and I’m going to write out please check if my a is not equal to my B and then is my a not equal to my C also and then is my b not equal to my C so in this condition here we check whether all of these three variables have different values here and if they do if this condition results as a true expression I’m going to write out let me just copy this and then we are going to adjust it I’m going to write out that my user has entered a scaling triangle as you can see here so when this goes in a yes way we write out that message so if this results as a true we write out that our user has entered scaling triangle but if this here results is a false then we are going to write out that our user has entered isosceles triangle and let me copy this like this okay so we have nested this if else statement inside this else block so this if else statement is going to execute only in a situation where this here results as a false F false expression so this code here if you find it a bit unreadable I want to show you one trick so one rule that you can really follow and that is if you have only one command under this if or else statement you don’t need to use these brackets so you don’t need to say that you are going to execute a block of code since you are not you are going to execute only one command so you can really delete th this here like this and then also here since we have only one command both here and here we we can delete these brackets here like this okay so now this code is a bit easier to read okay now as you can see from this diagram here it is literally translation of this here and vice versa so this code here is a translation of this diagram here and what it means is when our user enters three values for our sides of a triangle first we are going to check whether all of these three sides are equal if they are I’m going our program is actually going to say that our user has entered equilateral triangle but if this here results as false then we are going to our else block and then inside that else block we are going to Nest another if else so we are going to check another condition we are going to uh execute this if else here and this if else here is going to check for following so it is going to say please check if all of these three variables are different values so if all three sides of a triangle have different lengths and if they do we can say that that is a scaling triangle but if they don’t then since we have already checked that they are all that all of them are not equal and also we have checked here that all of them are not different we can say now that definitely two of these variables are equal and that means that our user has entered isoceles triangle and that is the program that we had here okay so I hope you like this video and if you did this is a strong call to subscribe to my channel and to share it with anyone else who would like to learn programming and I’m going to see you in my next video bye hi everyone welcome to another video of C++ for beginners in this video I wanted to talk about a operators in C++ and we are going to cover the ones that are used most of the time but I’m also going to make a separate video for certain operators that have specific use in C++ so in this video we will talk about the ones that are used most of the time and that you really need to know and understand and also make sure to watch the entire video because I do have some important tips to give you when it comes to this that you really need to understand and that you will find Handy for your future progress in learning of programming the first thing that I wanted to explain is what are operators you can understand operators as special type of functions that are used to perform certain calculations on arguments or operant and then based on those arguments and on that calculation they give you a new value so the first type of operators that I want to talk about are arithmetic operators and you are probably familiar with most of these so there is operator of adding and and subtracting multiplying dividing and also one more operator that you may not be familiar with which is the modulo operator so all of these are arithmetic operators and let me give you an example of how these are used so I’m going to say C out and then let’s write out the result of 5 + 2 and let’s add one end line okay so this here is the operator of adding and then these two are operant or arguments and this here is going to perform certain calculation and then write that out to my console so if I run my program we get the expected result which is seven so these really behave as you would expect them to behave in maths but there are certain rules that are specific to programming and that I want to mention so this operator here operator of dividing let me give you a simple example if I say C out and then five divided by two and I add end line what do you expect to see in this line here write that in the comments down below now I’m going to run my program and you see that the result that I’ve gotten from this line here is two but why has that happened we know that five divided by two is 2.5 well there is a certain rule in programming that says that the result of dividing two whole numbers like this so five is whole number and then two is also whole number is also going to be represented as whole number so even though the result of dividing D2 is 2.5 that 0.5 cannot really be put inside uh integer variable so it cannot be put inside integer container so just two can can be put here and that point two is really lost if you want to show the real result of dividing these two what you have to do is you have to make one of these two or both of them off a different type and that type is going to be decimal point number so float or double so if you put here 2.0 or you put here 5.0 then in this case you are going to get the result represented as decimal point number so you can use it like this or you can make just one of these of a floating Point type so you can say also like this and then if I run my program now you see that now I have got the expected result so 2.5 that is one rule that you really need to know when it comes to this division operator and another tip that I want to show you is this operator of modulo so how do we use this modulo operator this example here here that I’ve just shown you shown you let me return this to this situation where I’ve been dividing um two whole numbers and we’ve just seen that 5 ided by two is going to result as two and that one that remains we can get that one really with this operator here so if you say C out and then five modulo 2 add end line this operator here is going to give you the remainder of dividing two whole numbers which are these two so the result of this operation is going to be that one so let me run my program and you see that we have gotten that expected result so 5 divided by two when it comes to whole numbers if you’re dividing whole numbers the result is also going to be whole number and in this situation it’s going to be two and then that remainder after dividing two whole numbers you can get with this modulo operator and the remainder after after dividing five with two is one and you get it with this operator here so these five are really arithmetic operators and these are these are also called binary arithmetic operators why binary well because they are all used with two up runs they perform their calculation on two operant there is also another type of arithmetic operators in C++ that are used or that perform calculations on only one operant and those are unary operators the examples of unary operators in C++ are this operator here which is operator of increment and then this operator here which is the operator of decrement so how these are used let me give you example so let’s create a variable of type inth and let’s call it counter and I’m going to assign to that variable a value of seven for example so how this operator of increment works is it really increases the value of your variable by one so if I say counter counter Plus+ what this operator is going to do it’s really going to add plus one to my counter variable so 7 + one it should in this line here increase value of my counter variable to eight and let’s prove that oops see out counter and then let’s add one end line okay if I run my program you see that we’ve got expected result so eight we’ve declared a variable of type in called counter we’ve given it a value of seven and then in the next line we applied this increment operator to it which had increased its value + one so eight and then after we write out that value of that variable we got our result so that is how this increment operator is used this decrement operator so counter minus minus this decrement operator here Works uh reverse so it really subtracts one from this variable here and if I copy this line here and then paste it after this line here our counter should be decreased by one so the value of our counter should really again be seven and if I run my program oops like this you see that we’ve gotten our seven so we’ve gotten the expected result however there are specific rules when it comes to these increment and decrement operators and let me explain what I mean on another example so I’m going to create another variable of Type L int call it counter two and let’s assign it also a value of seven and what I want to do with this variable here is I want to write out its value but I want to write out and increment its value in a single line so I want to do this so see out counter to Plus+ and I’m missing this red Direction sign here okay so what are you expecting to see in this line here we’ve seen that this line here has resulted with eight and this line here should also result in eight let’s see okay run my program and it didn’t in this line here we have written out seven but why has that happened well this operator here is increment operator but it is really post increment operator and what that means is that whatever operation needs to be performed on this variable is going to happen first and then this increment operation is going to happen so that is called po increment another type of increment is pre-increment and it is used like this okay and this pre-increment means that whatever operation needs to happen on this variable here first I’m going to increment it and then I’m going to perform that operation so if I run my program now you see that we now get our eight same as here and that is because we have used this pre-increment which first has increased our variable and then our variable is written out okay and the same is applied for decrement operator so for example if I say C out counter to minus minus and then oh my God again okay and then if I run my program you see that we have gotten the same value for this line and this line so eight and why that has happened is because we have used this post decrement here so first our variable has been written out and after that the value of that variable has been decreased so just to prove that I’m going to say one more time C out and then counter two without any increment or decrement just to prove that uh the value of this variable has been decremented after it has been written out so if I run my program again you see that this line here has resulted in eight and then this line here has resulted in seven okay so you see that our console now is full of some random numbers and it’s really making it hard to read so what I want to do is I want to clear out my console but without deleting this code here so how I’m going to do that um I’m going to use a command that is called system and then inside these parentheses I’m going to say CLS which really is going to clear my screen so if I run my program you see that all of our code is still here but console has been cleared so that’s because of this command here that’s a quick tip if you need to clear your console another type of operators that I want to talk about are relational operators and these are really used to compare the value of two operant so two arguments and relational operators in C++ are following so we have less than and then we have greater than and then less than or equal to and then greater than or equal to then we have just is equal to operator and then we have not equal to so these six are relational operators in C++ and how these are used let me show you in an example so let’s say that I’m going to create a variable of type in call it a and let’s assign it the value of five and also create another variable that is called B and assign it value of five so now if I say C out and then inside this parentheses I’m going to say please write out if my if my V variable a is greater than my variable B so if if my five is greater than this another five okay and I’m using these parentheses because I want my C out command to know that this here is one expression that first should be calculated and then whatever this expression here results in I’m going to write that out in my cout command so if I run my program now you see that we have gotten zero and if you know about how computers work you know that they work on zeros and ones meaning that zero represents false and then one represents true so in this situation we have gotten the result of false so when I ask my computer is my a greater than my be so is five greater than five it says false no it is not okay and the same is going to happen if I put here this other operator of less than like this but if I for example put less than or equal to so this operator here and I run my program again you see that now we have gotten the result of one so that is true that is what our computers computer considers as true so our five is less than or equal to five which is correct and even better would be if we say just is equal to and in this situation also we are going to get true as a result like this because five is equal to five and then how we use this operator here is like this so you can say is my a not equal to my b and your computer really hears is my five not equal to my five and the response to that is going to be no it is false because these two are equal it’s the same number even though it’s held by two different variables okay I hope you understood these relational operators and there’s also one tip that I want to give you here and that is you see this comma sign here this is also operator in C++ and it is not really ational operator but it is binary operator and how this operator is really used because we have seen it before without knowing that it was an operator it is used as follows so in this line here we have said please create a variable of type int call it a and assign it value of five and then also so that is the purpose of my comma so also create another variable of type int call it B and assign it value of five so my comma in this situation is operator and separator as well so it is pretty intuitive so before we continue let’s add one more of these clear screen commands here and the next type of operators that I want to talk about are logical operators and there are three of those so we have logical and and then logical or and then also not operator so these three are logical iCal operators and they are usually used to combine two or more conditions into one single condition and I’m going to show you that on an example and let’s use for that example these variables here let’s just change the value of our B to eight for example so what I want to do is I want to write out following so is my a is my a equal to five and then also is my b equal to five I want to write out the result of this expression here and you see that we have used our end operator to combine these two expressions so if I run my program you see that the result of this is false so that is the nature of our end operator it really works like this it says please check is my a equal to five yes it is and then also check is my b equal to 5 no it is not it is 8 so then this operator says okay whatever then this whole expression is going to be false because this operator here needs both of its oper so this here and then this here also both of these need to be true in order for this whole expression to result as true expression that’s the nature of this end operator however there is one more forgiving operator in C++ and that is this operator here so this or operator and if if I place that here instead of our end operator and I run my program again you see that this time we got different result now we have true and that is the nature of our or operator so it says please check if this is true or this here is true whichever of these results as true then I’m going to be true expression only in the situation where this here is false and also this here is false I’m going to result as false in any other situation this here is going to be true so that is the nature of or operator and then we have also this not operator which really negates whatever comes after it so if I put it here for example you see that you’ve seen that previously this expression here has resulted as true expression now that I negate it we are going to get false so that is our not operator here okay and there is also one more thing that I want to explain when it comes to the procedence of these operators which means priority of these operators so which operator types have the biggest priority uh the biggest priority have arithmetic operators after that come these relational operators and then the smallest priority already have these logical operators so let me show you that on an example let’s just comment this very quickly and let’s add another line but the previous one that we had so this here like this that is the operation that has resulted as false so is my a equal to five and then is my B also equal to five and this has resulted as false but if we for example say it like this what do you think that this expression here is going to write out so if I run it you see that we have gotten one why is that so well as I’ve said the biggest priority have arithmetic operators so this expression here is going to be executed first so 5 + 3 after that priority have these relational operators so this operator here and this operator here so after that comes logical operation so so this expression here is going to be really is my a equal to 5 yes it is and then also is my b equal to eight and the answer to that is also yes so now both of these operant are true and our end operator is satisfied now and it’s going to result as true operation this whole expression so you need to remember that the biggest priority have arithmetic operators so these here so these here binary and unary arithmetic operators after that we have our relational operators and then the least priority have these logical operators here let’s add one more of these clear screen commands before we talk about the last type of operators that I want to cover in this video and those are operators of assignment and there are six of those and there are a follow so operator that just assigns value and then operator that adds and assigns and then operator that subtracts and assigns multiplies and assigns divides and assigns and modulates and assigns so these six are operators of assignment and let me show you how they work so first I’m going to create a variable of type end and let’s call it X and let’s assign it a value of for example five okay so this here is example of this assignment operator here and that is how it works it assigns whatever is on the right to your variable on the left so that is the direction of Association it really says whatever is on my right side Please assign that to my left side and let me show you know how these here work because they’re a bit more complex so if I say for example x + = 7 like this what this expression here is going to do well let me write out one more expression and that is X = x + 7 so this expression here and this expression here are just the same this is just shorter way to write this here and what this here does well this is expression that is not valid in mathematics but in programming it is and it does following so it says please whatever is on my right side assign that to my left side and why it does that well because this arithmetic operator here has priority over this assignment operator so if you remember when we were talking about priority these assignment operators have the lowest priority of all so whatever is on my right side that is x + 7 is going to be assigned to my X variable so 5 + 7 is going to be equal to 12 and then that is going to be assigned to your X variable in this line here and this expression here is really short way to write this here okay so I’m going to comment this out and if I write the value of my X now we are expecting to see 12 and it is the result that we have gotten so this x +al 7 is just going to do this so this expression here so it’s going to add to my X this number here and the same applies to these operators here so this one that subtracts and then assigns or multiplies and assigns divides and modulates so if you say for example x minus equal to 7 then that is really going to result as X is equal to x minus 7 and then that right side is going to be assigned to your left variable because arithmetic operators have priority over these operators of assignment and if I run my program again it really sees 5 – 7 and that is minus 2 so I hope that you have understood these examples that I’ve just given you and I’m also going to include some more examples at the end of this video but tricky want so that you can be sure that you have really understood these operators in C++ because they are used very often and you have to understand them in order to continue with your progress on a programming path so make sure to do those examples on your own and if you come across any problems or you have any questions that are related to this video write those in the comments down below and I’m going to answer them I’m going to help you and if you likeed this video make sure to subscribe to my channel and also click the Bell icon so that you are are first to be notified when I publish my next video and I’m going to see you in my next video bye hi guys welcome to my channel in this video I wanted to answer a question that I recently got and that is a question that is often asked on job interviews and also students get it on their exams and that is a question on how you can swap the value of two variables I’m going to give you two ways to solve this problem but let me just explain what I mean by this so I’m going to copy the text of this problem here like this and let me say that I have one variable which is going to be called a and that variable is going to hold value of 20 let’s say and then I have another variable which is going to be called B and that variable holds value of 10 and now I need to switch the value so to swap the value of these two variables I want my a to hold whatever my B is holding and then I want my B to hold whatever my a is holding so how we are going to do that for the first explanation I will need something so let me get it so here I have two glasses and inside this left glass I have my green juice and then inside this glass I have just plain water and the question that we have in our our Visual Studio is equivalent to a question how we can swap the content of these two glasses and to solve that problem I’m going to use another glass so a temporary glass and that is this one here and I’m sorry guys I know this is not a glass it’s a Shaker but it will do for this explanation so what I’m going to do is I’m going to take this this glass this variable and I’m going to put its content inside this third glass this temporary glass okay and then when I have saved the value of this glass inside this temporary glass what I can do is I can put my green juice so the content of this glass inside here okay this is a bit more complex in real life than in programming so once you do that you have saved the value of this glass here so the content of this glass here inside this glass and now what we are left to do is just to put whatever our temp variable our Temp Glass was holding inside this glass here and now we have successfully accomplished to solve this problem so we have switched the content of these two glasses and let’s just translate this into our code now that I have explained the algorithm to solve this problem we are just going to translate that algorithm into C++ code so the first thing that I’m going to do is I’m going to create a variable a temporary variable which I’m going to call Temp and inside that temp variable I’m going to put whatever my a is holding so I’m going to say that my temp holds now whatever is inside my a variable and since we have our a variable free now to hold something else I’m going to put my B value inside my a so now my a is going to hold whatever my B is holding and now that we have saved the value of our B inside our a variable we can put inside our B whatever our temp variable is holding so that is the value that previously was inside our a variable and this here is really the algorithm to solve this problem using a third VAR variable and let’s just quickly add a c out so that we can see what we have done so our a is equal to a and then our B is equal to RB and let’s add end line like this and I’m going to add just a comma sign here okay and if I run the program you see now that here we have a is equal to 20 and B is equal to 10 and now we have successfully swapped the value of these two variables so now my a is holding 10 and then my B is holding 20 which previously was inside my a variable and this is a solution for our problem using a third variable but this question is often asked in another way and that is how you can swap the value of two variables without using a third variable and now I’m going to explain that so let me very quickly delete this until here okay and in order to solve this problem without using third variable you will have to think in a more mathematical way and the solution for this is going to be the following so the first thing that I’m going to do is I’m going to say okay let’s say that my a variable is going to hold whatever my a is holding holding and I’m going to add whatever my B is holding also and this expression here would be really incorrect in any mathematics but in programming this is this is a valid expression and it means this here whatever this expression results in I’m going to assign that to my a variable and this here is whatever my a is holding plus whatever my B is holding assign that to a so that is going to be a so 20 + B 10 that is equal to 30 so now in this line here my a is going to hold the value of 30 and then in the next line let’s say now my B is going to hold whatever my a is holding and then subtract whatever my B is holding from that so in this line here I’m going to say store inside my B the result of this expression here and this expression will result in following a so 30 minus b – 10 that is going to be 30 – 10 20 so in this line here my B is going to hold the value of 20 and then what we are left to do is just to put the correct value inside our a and that is going to be a = to a minus B this means whatever my a is holding at this very moment and that is 30 minus whatever my B is holding at this very moment and that is 20 and guys 30 minus 20 is going to result in 10 and our a is going to get the value of 10 in this line here so now if I write out C out a is equal to a and let’s add and line and then C out B is equal to B and if I run my program you see that I’m going to get the expected result so my a now is holding whatever my B was holding so 10 and then my B is holding this value that previously was inside our a variable here so we have solved this problem in two ways so with or with without a third variable so if you found this video helpful make sure to like it and to subscribe to my channel and also any questions that you have leave those in the comments down below and share this video with anyone who’d like to learn programming and I’m going to see you in my next video and also guys one question for you if you have any recipes any algorithms on how you can make green juice taste and smell good please make sure to write those in the comments down below bye hi guys welcome to my channel welcome to another video of C++ for beginners I just got an idea of a simple and fun program that I can show you how you can build and since I’m a bit of a fitness Enthusiast myself if you haven’t noticed uh I wanted to show you how you can build your own body mass index calculator so stay tuned make sure to subscribe and let’s build our own BMI calculator okay so here is the text of my task and what we are going to build is BM calculator so first I want to explain what is BMI calculator it is body mass index calculator that is going to tell you whether you are underweight or normal weight or you are overweight depending on your weight and your height and here I’m going to use weight in kilograms and then height in meters so if someone else wants to adjust this program so that it can work with pounds feets and inches you can write out that code in the comments down below and the first one that gets it right I’m going to pin that comment so that everyone else can use it and see it okay so we are going to use this formula here which is used to calculating your BMI in metric system so another thing that I want to mention is this these three categories here there are also some more categories that you can really calculate whether you are extremely underweight or you are extremely overweight but these three should be enough for us to do now and these three I’m going to cover in this code another claer that I want to make is that this BMI calculator probably should not be used by people that have huge amounts of muscle so professional bodybuilders because even though they have muscle that muscle is still weight so even though they are not overweight they will fall in a category of overweight because their BMI is going to be higher but for most of us that don’t have a lot a lot a lot of muscle or are leaving normal lives training couple of times a week maybe this is going to be completely okay so let’s build our prog program now so here is our tool that we are going to use to draw this diagram so Lucid chart and let’s really develop the algorithm for solving this problem and then we are going to translate that diagram that algorithm in C++ code so as you may already know first thing that I’m going to put here is this shape here that is going to indicate the start position of my program this circle shape here and after that we really need two things from our user so two things that he should enter and those are his height and his weight so let’s use this funnel shape here that is going to indicate something entering in your program so visual representation that’s why I’m using that funnel shape and inside here I’m going to put two things that my user needs to enter and those two things are these two tanks here so his weight and he should enter his weight in kilogram and also his height and let’s say that he should enter his height in meters so I’m going to use metric system for this problem okay and let’s indicate the flow of our program it should flow like this and after our user has entered his weight and his height there is a simple calculation that our program needs to perform and that calculation is going to be a process for our program so the shape that I’m going to to use for that is this shape here so this shape that says process on it and what our program should process what our program should calculate is it should calculate BMI so I’m going to put here BMI is equal to and then I’m going to put this formula here that is used to calculate BMI okay so it’s weight represented at kilog divided by height to the^ of two so I’m going to multiply my height with height okay and this is really the calculation of our BMI and now after our program has calculated this BMI what we are left to do is we should depending on this BMI really write out to our user whether he’s underweight or overweight or of a normal weight so we should make a decision depending on this BMI and for that decision we are using this decision shape so this diamond shape and inside this diamond shape I’m going to put I’m going to put a condition and that condition is going to be let’s first check whether my BMI is lower than 18.5 like this and in this situation where our user’s BMI is lower than 18.5 so when this condition here results as yes I am going to write out something to my user and let’s me find a shape okay let’s rotate this shape and delete is text okay and what I want to write out to my user oh I can make this smaller what I want to write out to my user in the situation where his BMI is lower than 18.5 is I want to write out that he is really underweight so let’s put text inside here and let’s write out that he is underweight so that is going to happen in this situation oh my God that is going to happen in this situation here let me just okay now it’s okay so in this situation where his BMI is lower than 18.5 we are going to write out that he is underweight but in the situation where his BMI is not lower than 18.5 we have to check something else and let’s check so let’s add another another of these diamond shapes where is it here okay and let’s now check whether his BMI is higher than 25 so I’m going to write out BMI greater than 25 okay and that is going to happen in the case that this here results as no and in the situation where user’s BMI is higher than 25 that really means that our user is overweight so we are going to write out of okay so we are really going to write out a message to our user so let’s copy this shape here which we are using to write out a message to our user so this reversed finnal shape that represents something leaving your program something being outputed from your program so in the case where this calculation here results as true we are going to write out to our user that he is overweight like this okay and let’s really adjust this now it’s now it looks a bit more presentable okay so first we have checked whether his BMI is lower than 18.5 is if yes we have written out underweight if no we have to check whether his BMI is greater than 25 and if it if it is it means that he’s overweight but in the situation where this here results as a no that means that our user BMI is not lower than 18.5 nor it is greater than 25 so that means that his BMI is really somewhere in between so between 18.5 and 25 and that is a normal BMI so that is our last possible situation where we are going to write out to our user that he has a normal weight so let’s write out normal normal weight okay so after we have covered these three cases cases let’s just join our flows into one so I’m looking for this shape here and I’m going to make it smaller delete this text from it and I’m really just going to join these flows inside this shape here let’s let’s just try to move this here I’m going to delete it and let’s say that I’m going to oh no [Music] okay guys I had huge problems trying to adjust some arrows so I had to rewrite this whole diagram and I believe that I made it a bit prettier so here we were explaining that in the case that our user has BMI lower than 18.5 we are going to write out this message to him in the case that his BMI is not lower than 18.5 we are going to check whether it is greater than 25 and if yes we are going to write out that he’s overweight if no we are going to write out that he’s of normal weight and in each of these three cases we are coming here to this diamond shape here which is just just going to join these three potential situations and after this diamond shape here we are going to write out to our user what his BMI really is because I really want my user to know if he’s for example in this situation here or in this situation here I want him to know whether he’s BMI is let’s say 18.4 so he’s not that extremely underweight but he’s just a little bit underweight or in this situation here I want him to know whether his BMI is 25.5 so he’s just a little bit overweight or his BMI is really 35 let’s say that’s why I I want to write out my BMI to my user his BMI to my user okay so and then we just released upop our program so now I’m going to copy this diagram and put it next to my visual studio so that we can really translate this this diagram here into our code so here I have put this diagram and then also my visual studio and let’s now translate this diagram let’s translate this algorithm and to code because this here really is an algorithm explanation on how to solve a certain problem so the first thing that needs to happen is our user should enter his weight and his height and for that to happen I first need to declare variables for weight and height and for that I’m going to use type float because his weight and height can be decimal point number so I’m going to say float and then I’m going to say weight and height okay like this and after that let’s put a message out to our user so that he knows that he should enter his weight and height so I’m going to say C out weight and let’s put that here should enter his weight in kilogram and then also height but he should enter his height in meters like this so that he knows which which system he should use okay after we have written out this message here what I need to do is I need to use my C in command so that I can allow my user to enter weight and height and I’m going to say first thing that my user enters that’s going to be stored inside my weight variable and then after that the second value that my user enters is going to be my height so store that in a height variable like this okay and after we have entered weight and height next thing that needs to happen is we need to do this formula here and really calculate our BMI and in order to store this result the result of this expression in our BMI we need a variable for that and that variable is obviously going to be called BMI so let’s add here in this line here let’s add BMI so I’m going to declare another variable and that variable I’m going to use now and I’m going to say that my BMI is going to be used as follows so I’m going to use this formula here which is our weight divided by our height to the power of two for now I’m going to use use it like this okay and and in this line here we have really calculated our BMI so this code here and now after we have calculated our BMI what we should do is we should really check what is the value of that BMI and for that we are using this shape here which really translates into if if else case so first I’m going to say if and then the first thing that I want to check is if my user’s BMI is lower than 18 5 like this and in this situation where his BMI is lower than 18.5 I’m going to execute one line of code so that’s why I don’t need to put these brackets so I’m going to delete them because I just want to execute one line of code and that line of code is going to be indented here so that it is easier to read and that line of code is really to be going to be a message that I want to write out to my user and that message is going to be that my user is underweight unfortunately okay and let’s add one end line like this okay this is in the situation where his BMI is lower than 18.5 in a situation where his BMI is not lower than 18.5 we are going to execute something else so that something else we represent with else statement and I’m going to put that lse statement and what is happening in that else case it is happening another if else so here we have a situation where we need to check something else so here I’m going to put else if so if this here results as no please then check something else and for that we use this else if statement so I’m going to say else if please check if my BMI is greater than 25 then so in this situation we also want to execute one line of code and that line of code is going to be to write out to my user that his BMI is greater than 25 which means that he is overweight so let me copy this message here and we are just going to adjust it so I’m just going to say you are overweight like this okay so if his BMI is less than 18.5 I’m going to write out that he’s underweight else if his BMI is not lower than 18.5 I’m going to check whether his BMI is greater than 25 if yes I’m going to write out that he’s overweight if no we are also going to execute something else and that that is this situation here so in this case he has a normal weight so let me again copy this message here and let’s really put here a normal weight like this okay so in this situation where his BMI is not great not lower than 18.5 nor it’s greater than 25 we are going to write out our user that he has a normal weight and with this here with this code here we have really covered this part of diagram here okay and then after this code here executes we really want to write out our BMI to to to the user so we have to this shape here which really translates into our our C out command and we want to write out your BMI is and then let’s write out BMI like this okay and this line of code as you may already see from our diagram is going to execute in either this case or this case or this case because after we have finished with this decision part we have executed only this part of codee or this part of code or this part of code here so whichever of these three has been executed after this code here we are going to execute this line here in either this situation or this situation or this situation and that is going to be writing out to my user what his BMI really is and that is the last thing that we need to put so the last part of our code and now if I run my program okay it asks me to enter my weight and my height and my weight is I believe 6 66 kilg I think and then my height is 1.75 so let’s press enter oh no I’m overweight how my BMI is 6 6 okay guys for a moment I thought that I am overweight but I am not definitely this 66 BMI overweight so that means that we have a bug so where are you sneaky little buggy bug well if you can see where our bug is then write that in the comments down below and I already see where potentially our bug could be so this formula here it should really go like this so we should divide our weight with our height to the^ of two which means that we should put parentheses here like this because and that is this calculation here so in this situation our weight is going to be divided with our height and after that that number is going to be multiplied with our height so we are going to get larger BMI than we should really so we should put this code here in parentheses so that was the first bug that really happened in these tutorials okay I’m going to leave this part I’m not going to edited out okay and now if I enter my weight um let’s see 66 and then my height 1.75 okay so I am 21.5 that is my BMI and I am off a normal weight so we have really built our BMI calculator and this is the formula that you should use for metric system and if someone else wants to rewrite this program for pounds and inches and um feet you can write that in the comments down below and as I said I’m going to pin that comment up so that everyone can see it if you of course get it right I hope you like this video if you did make sure to write it in the comments down below and I’m going to put more videos like this and also subscribe to my channel and click the Bell icon so that you are first to be notified when I publish a new video share this video with anyone who would like to learn programming or also with Fitness people that would just like to use this program and if you don’t know how you can run this program without using using visual studio I’m going to link my first video here and at the end of that video I’m explaining how you can run the program from Windows and that should give you an idea on how you can really share your applications with other people so make sure to subscribe like leave a comment share whatever you want and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners in this video I wanted to explain the concept of turnery operator also known as conditional operator and also some people call it shorter version of IFL statement it is an important concept that you are definitely going to come across in your programming career and you should understand it and I’m going to explain this concept through building fun and simple program that is going to be a guessing game so let’s explain the rules of this game we need to have two users and our first user which I’m going to call host user has to enter a number after that we have to delete that number from our console so that our second user cannot see it and then after that our second user which I’m going to call guest user has to enter his guest so that he can guess what number our first user has entered so this way we can really make a fun program and learn an important concept at the same time and at the end of this video I’m going to give you an idea or multiple ideas how you can really upgrade this program on your own so make sure to watch the entire video now that we have explained the rules of this game let’s start building our program and the first thing that we need to do is create two variables since we said that our user is going to be guessing numbers those two variables are going to be definitely a number type and let’s say that that type is going to be integer so integer numbers and we need two variables the first one is going to hold our first user number so our host user number and then our second variable is going to hold the number that our guest user enters so let’s call those to host user number like this and then the second one let’s call guest user number like this okay and now after we have created these two variables the next thing that we need to do is let’s write out a message to our host user so that he knows that he should enter a number so let’s say see out and let’s just say host like this so that our host user really knows that he should enter a number and I’m going to accept that number in my console using the C in command and I’m going to store that number inside our host user number variable so with this line here we have entered our host user number and what we have said at the beginning of this video is that after our host user enters the number we really need to delete that number from our console so that our second user is not able to see it and the command that I’m going to use for that is going to be this command here so I’m going to say system and then I’m going to say CLS which is which is really going to clear our console so clear our screen and now if I run my program let’s see how far we have made made this program here we have this line This seventh line which says host user and it expects our host user to enter a number so I’m going to say for example seven and then after I press enter this number here really is deleted so our console has been cleared and now after this we need to ask our guest user to guess the number that our host user has entered so I’m going to stop the program and next we need to write out a message to Our Guest user so I’m going to say guest like this and after that we need to accept what our guest user enters inside our guest user variable so I’m going to copy this line here like this and instead of accepting that value inside host user number I’m just going to change this to guest user number and after this part here we really have both accepted our host user number and our guest user number and now we need to compare these two and see whether our guest user has guessed correctly our host users number so how we can do that if you are familiar with f l statements and I’m going to link that video here and if you are familiar with them that is really one way to solve this problem so you can solve this problem with IFL statement and I’m going to do that and then we are going to really convert that IFL statement inside into a tary operator so how we can solve this with IFL statements well it is quite simple solution so we have to say if and then inside these parentheses I’m going to really compare these two numbers so host user number and guest user number so I’m going to say host user number is equal to guest user number like this and then if this here results as true so if these two if these two numbers are the same we can write out a message to our user and that message is going to be let’s say correct like this so our user has guessed correctly but in a situation where this here results as false we can use our else statement and in this else situation let’s write out a different message to our user so let’s say see out and then inside this these quotation marks let’s say failed like this so that in the case where these two are the same number we can write out to our user that he has guessed correctly and then in a situation where these two are not the same we can write out to our user that he has failed in guessing so if I run my program now you see that it expects our host user to enter a number and I’m going in this situation to take the role of both host and guest user so I’m going to enter seven for example and then you see that that seven number has been deleted from our console because of this command here and now our program expects Our Guest user to enter his number and I even forgot what number I entered so let’s say that our host user has entered for example 11 and you see that our program says you have failed so you haven’t guessed correctly and one more time let’s enter for our host user number five for example and then let’s say that our guest user also says number five and our program says you have guessed correctly so this is one potential solution for this problem but I wanted to show you how you can solve this problem using Turner operator and now I’m going to comment this code here like this so this is a comment for multiple lines of code and let’s really translate this part of code here into a turn operator like this okay so how does theary operator work well it is the only operator that takes three op runs or works on three operands and the first opun is going to be a condition so I’m going to copy this condition here which is is our host user number equal to Our Guest user number so that is going to be the first uun and after that first uun we need to put this question mark and then after this question mark we have the following Behavior if this expression here so if this condition here is true we are going to execute one line of code or actually one part of code and that is going to be this line here but in the situation where this here results as false we are going to execute whatever we put after this column sign so that is going to be our C out failed like this and this is really the Syntax for our Turner operator and as you can see it really is a shorter form of if else statement so this line of code really means please check this condition here and if this condition here results as true execute this part of code here but if this code here results as false please execute whatever I put after my column sign so that is going to be our see out failed and now if I run the program it asks again for our host user to enter the number let’s enter number nine for example and then our guest user has to guess the number so let’s enter for example number three and you can see that our program says to Our Guest user that has failed in guessing so there are a couple of ways in which you can really upgrade this program and I’m going to give you a few ideas and the first one is for example you don’t have to use int type here so you can use different data type data type you can guess characters or you can guess even strings if you know how to and if some of you want to play with that and try that on their own and you get it right make sure to paste that code in the comments down below and I’m going to check it and if you get it right I’m going to pin that comment up so that everyone else can see it so that would be one way of upgrading this program another way to upgrade this program is to make it easier to your guest user and how do I mean easier well you can really limit your host user to enter a number that is going to be in a certain interval for example you can say to your host user that he can enter only a number that is going to be between let’s say 1 and 15 or 50 it depends on how difficult you want to make it to your guest user and that would be one way also of upgrading this program and another and the best way of upgrading this program is going to be when we learn loops and when we do that I’m going to link the video here and how you can upgrade this program using Loops well you can give your guest user multiple attempts so you can say for example let my guest user guess three times or five times before I say game over you have failed okay so I hope that you have liked this video and if you did make sure to subscribe to my channel share it with your friends and with other people that would like to learn programming and I’m going to see you in my next video bye hi guys welcome to my channel welcome to another C++ for beginners tutorial and I’m really excited for making this video because this video is going to be a milestone and in this video I’m going to show you how you can build your own calculator application so if you have watched my previous videos and you are also so watching this one and you build this application together with me you should really feel proud of yourself because you have made a great progress so let’s build that application now here I have opened my visual studio and let’s very quickly explain what we want to do before we start write code so I want my user to enter two numbers and also operation sign and then depending on those two numbers and that operation we want to calculate the result and then write that result to our user so so the first thing that we need to do is we need to declare variables that are going to hold those numbers and that operation sign and since we want our user to be able to enter decimal point numbers so not only integers but decimal point numbers as well we are going to declare variables that can hold decimal point numbers and those can be float and uh double so let’s declare float variable for example and let’s call it num one which is going to hold our first first number and also another one which is going to be called number two and hold our second number and after we have declared these two let’s also declare a variable that is going to hold our operation sign and since that is a character we need to use a character type for that variable so let’s say Char and let’s call that variable operation like this okay and now after we have created these three variables we can really allow our user to enter his numbers and his operation and we want to do that in the following order so we want to say C in and then first our user has to enter the first number and then after that we want our user to enter the operation sign so let’s say operate operation like this and after that our user has to enter the second number and this window here guys this is called Intellis sense and it really makes your code writing easier so you can navigate this list here using your arrows and then you can also use tab key so that it finishes your variable name for you if you want that okay so now we have entered our first number our operation and then our second number as well like this and another thing that I want to write out to my user because this is going to be the best calculator ever let’s write that uh title for user so let’s write here before he enters anything a quick title so let’s say see out and then let’s say that it’s going to be called code Beauty calculator you can call yours whatever you want so like this and let’s add these here so that it looks prettier okay and now if I run my program well you see that it really looks like this and now we are able to enter one number after that we want our user to enter operation like this and then we want to enter the second number like this and then after we press enter our program should really calculate the result of this operation in this current situation it is not really doing anything else because we haven’t written code for that okay so now let’s solve this problem that we have here so at this point you should really have an idea yourself on how to solve this problem using IF El statements and also nested IFL statements so if you are not familiar with those I’m going to link one of my previous videos here so make sure to watch that video as well but in this this video I want to show you the more appropriate way for solving this particular problem and that is going to be using switch case statement so what is switch case statement well switch case statement is as well as if else statement used when you want to execute a block of code depending on a certain condition so depending on a value of a certain variable but switch case statement is particularly used in a situation where that variable can potentially hold a lot of different values and if you look at our operation variable here you should really notice that this variable can hold six different values and what are those six well our user can decide to enter operation for adding subtracting multiplying dividing modulating and then what if our user does not really want to use our application but he wants to hack it so if he decides that he doesn’t want to enter one of these five but he really enters some nonv valid arithmetic operation we should also cover that case so we should really as programmers predict all these six situations and cover all these six cases I’m going to add one end line here so that my text is formatted nicely and then let’s really show how this switch case statement is used so the first thing that I want want to write is switch like this and then if you press tab you see that you are getting some default Syntax for this switch case for now I’m going to delete that and I want to show you how you can really write that yourself and inside these parentheses here I want to write out the name of my variable that I want to switch through or switch on and that is going to be my operation variable because depending on the value of this operation variable we are going to perform a different calculation on these two number variables so I’m going to say here operation and then in these curly brackets here we really want to cover all our cases so the first case let’s say that our first case is going to be a situation where our user enters minus operator so I’m going to use these single quotes and then inside the single quotes I’m putting the value that our variable can potentially hold and that is this minus operator here and after that I’m going to add this column sign here like this and then after this column sign I really want to put out whatever code I need to execute in the case that our operation corresponds to to this sign here and what I want to execute in this case is I want to say see out and let’s WR write out our first number and then let’s write out our operation and then let’s write out our second number so that our user really gets a night nicely for method text and after that I’m going to add this is equal to sign and here we are going to put really our result and that result is going to be our first number minus because our user has entered this minus minus so our first number minus our second number so let’s write out number one minus number number two like this and after we have covered this first case we need to add one more keyword and that is going to be break and this break keyword is really used so that our switch case statement knows where our first case ends so I’m I’m saying here whenever my operation is equal to this sign here you are going to execute this code and you should really stop executing this CA that case when you come to this break statement okay so this is going to be our first case our second case is going to be situation where our user let’s say enters this plus sign and in that situation we really want to write out to our user this text here so the same text we want to really write out our first number Plus in this case our second number and then is equal to and then we are going to add really this calculation here so number one plus number two like this and in this situation as well we want to add this break statement at the end like like this okay so these are two potential cases and now I’m going to really write out the rest of them so I have written out these remaining cases and in each of these cases we really want to write out our user his first number after that his operation second number and then this equal sign and then in each of these cases we are performing adequate calculation so we are performing that operation that are user has entered and writing that result out to our user and after each of these cases we really need to put this break statement and you really have to put this break statement because if you don’t you are going to get your program to behave as you don’t want it to and as you can see in this situation here so in this situation where we are trying to modulate two numbers we are getting an error and if we hover over this number here you can see that our error says expression must have integral or unscoped enum type what does that mean well if you haven’t watched my video on operators I suggest you to do so I’m going to link it here and here I’m quickly going to explain what is happening so this operation here this modulo operation is Operation that is really going to give you a remainder after dividing two whole numbers and since this number here and this number here are of type float we really cannot perform this calculation on these two variables so what we have to do is we first have to check whether this number is really a integer number whether it’s a whole number and this number as well and since our float can hold decimal point numbers and integers as well we really in certain situations only can perform this modulating operation and let me explain what I mean by this that our float can hold can hold decimal point numbers and integers as well well this variable here this number variable can really have a value of 5.5 for example but it can hold as well value of 5.0 which is really integer value so it’s 5 only so now what we have to do is following I’m going to delete this line here and we first have to check whether both of these numbers are integers and in that situation only we can perform this calculation but in a situation where one of these two or both of them are not integers we are going to write out to our user that that operation is not valid so I’m deleting this code here and then let’s create two variables so let’s create a variable of type Bull and let’s call it is num one integer so this variable is going to hold a value that is going to tell us is our our number one integer value and let’s also create another variable that is going to be called is num two int and as well this variable is going to tell us whether our number two is integer and let’s develop now an algorithm so that we can know whether our number one or number two is integer number and I’m going to ask you to write your Solutions in the comments down below so pause the video think about it and then write your solution and without using any already made functions as programmers as Engineers you should really be able to figure out the solution on your own so applying the knowledge that you have gotten from my previous videos or this one but I’m going to say from my previous videos so pause the video and write your solution so this question is not really a question of programming it’s more of a question of thinking in a logical way and if you remember when we were talking about casting operators we said that a casting operator is used to convert one data type into the other and I’m going to link that video here if you haven’t watched it make sure to do so and here we are going to try to convert our floating Point number so our number one and our number two into integer data type so into integer number and how we are going to do that well we are really going to say int so this here is going to cast whatever we put after it into int type and we are going to say please try to convert my number one into integer and how does this work well for example if you have a number one that holds value of 5.7 when you try to convert that value into integer what it does really it says that 5.7 so that7 part really bye-bye I’m going to take only this five part so only this whole part of a number so in that situation we are really going to get only five from this 5.7 floating Point number so what I’m going to say now is I’m going to say whatever this expression here this casting operation results with I’m going to really try to compare that with the initial value of my number one variable so I’m going to say num one is my converted number one so converted to integer equal to number one like this and how does this calculation here work well as I said for example if you have a number one that holds a value of 5.0 so 5.0 this part here is really going to take this 0 Z part of a number and delete it it’s going to keep only this five so only this whole part of a number and after that we have this is equal to operator and then we are trying to really uh trying to really check whether that is equal to 5.0 and the result of this is going to be true so we with this here we have checked really whether our number is going to be equal to our floating Point number so this result here we are going to assign this value to our is number one integer variable so here I’m going to say Please assign the result of this operation to our is number one integer variable like this and let’s put this expression here so this whole expression inside these parentheses so that we really can see that this is an expression and the result of this expression should be assigned to this is number one one in variable and now we are going to do the same for our is number number two so I’m going to say is number two integer and we are going to say that that is equal to I’m trying to convert my number two to in and then compare that to my float number two and after this we really can now do our algorithm to perform this modulo where it is this modulo operation on our two numbers in the case where both of them are integers so here I’m going to say if is my number one int and then also is my number two int like this in this situation here I’m going to perform this modular operation and as you can see here I have used only these two bull values here in this expression so I didn’t say please check is my number one int equal to True like this nor I have said please check is my number two equal to True like this because uh this here this part here and this part here are really redundant and what this expression here translates in it translates in is true equal to true and that is really redundant so I’m going to remove this part here and this part here and it should work fine like this for Boolean values so Boolean variables and in this situation here where both of these are integers we really can perform this modular operation so in this situation here I’m going to take this code and I’m going to copy it like this and I’m going to say please write out my number one then my operation then my number two is equal to sign and then here I’m going to put adequate calculation so I’m going to say take my number one convert it to to int and then modulate that with my number two that is as well converted to int like this okay so in this situation where both both of these are integers we are going to really write out the result of modulating operation to our user let’s add empty space here and here as well but in the situation where one of these two is not integer or both of them are not integers I’m going to say else and in that situation I really going to write out my user that this operation is not valid so let’s say just not valid like this so in any of these two situations whether we write out this line of code here or this line of code here after that we are going to come here and here we have to put our break statement like this so after each case comes break and now we can really test this part of code here that we have written so if I run my program the first thing that that I want to test is let’s say 5.5 Plus 2.2 and we get the expected result so 7.7 let’s run our program again and this time I want to check whether my modulo operation is working as it should because this code here is really specific so let’s say five modulo 2 like this and as well we have gotten correct result and let’s run our program one more time and here I really want to trick my program and try to make it to modulate two numbers that are not whole numbers so 5.2 modulated by two and as well our program works as it should so it says not valid operation okay so if you have noticed uh in this current situation I really have to run my program each time that I want to perform a calculation and that is because we haven’t learned anything about iteration or loops so far and those videos are coming so make sure to subscribe to my channel and also click the Bell icon so that you are notified when I publish those videos and in that situation where we learn iteration and Loops we are really going to be able to run our programs indefinitely which means to run our calculator application until we really decide to stop it okay so after we have covered these five cases here there is only one situation left to cover and that is situation where our user enters any other sign that is not one of these five here and that situation we are really going to write like this so we are going to say default so in the case where our user enters operation that is not going to correspond to any of these five signs we are going to execute our default situation and here we really want to write out a meth message to the user that is trying to hack our program so you can write whatever message you want to the user that is trying to hack the program that you have worked so hard to build and I’m going to put here okay you really can write out whatever you want to that type of user like this so in the case where our user has not entered this nor this nor this nor this nor this which means our user has entered some other sign we really want write out not valid operation and let’s test now our default case so I’m going to run the program and I’m going to take the role of a malicious user that is going to try to hack your application and I’m going to say please try to perform this calculation here so 5 z9 no not really you have been smart enough to predict his malicious behavior and you have said if you haven’t put here a valid arithmetic operation then no I cannot help you this is not a valid operation and there is really one thing that you have been wondering about for the most part of this video and that is this break statement here so why I have said that after each case you have to put break and now you want me to explain that do you do you really wouldn’t that be a spoiler for a situation where you decide on your own to delete this break statement here and then run your program even though I have said not to and you enter some calculation and you remember that I have said that you are going to get unexpected Behavior but was she lying was she not and then you decide to execute this calculation and boom here is your unexpected Behavior so what has happened here well your program has really recognized that this operation here that you have entered is this minus operation and after that is it has written out this number one so 7 and then operation minus and then this number two five is equal to and then it has calculated number one minus number two which is 7 – 5 and that is equal to 2 and after that it has really continued executing other cases which means it has come to this line here and then then it has written one more time your number one minus number two so 7 – 5 is equal 2 and then it has performed this number one plus number two calculation and 7 + 5 is going to be equal to 12 and then it has come to this first break command and it has has stopped the execution of your switch case so why has this happened it has happened because you haven’t put this break command here and in that case program is really going to be executing your cases until it comes to the first break command and if you have noticed here in this default situation I haven’t really put any breaks you can as well put your break statement here you can say break here but even if you don’t if even if you didn’t put your break here and your program really tries to execute something after this line here there is really nothing to execute so you are not going to get a problem in this situation here I hope that you like this video and that you have built your own calculator application and if you did make sure to subscribe to my channel and click the Bell icon as well share this video with anyone who would like to learn programming and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners and in this video I wanted to deepen your knowledge of switch case so if you’re not familiar with switch case Cas at all if you haven’t watched my previous video you definitely have to do that the link is going to be here and in this video I wanted to give you some more examples that you can practice on and introduce some things that I haven’t mentioned in my previous video as well so in this video we are going to build a program that is going to require from our user to enter a year and a month as well and then our program has to write out how many days there is in that month so how we are going to do that let’s see but first you have to subscribe to my channel and like this video and also share it with your friends as I explained there are two things that we need from our user to enter and those are going to be month and year so let’s create two variables let’s say year and month like this and now I’m going to write out the message to my user so that he knows that he should enter those two values so year and after that please enter month like this and let’s store now the values that our user enters so the first one is going to be stored inside our year variable and then the second one is going to be stored inside our month variable and now we have really covered everything that we need from our user now our program has to check these two variables and then decide how many days there is in that month of that year and we are going to do that using switch case statement but but there is one thing that I want to mention before before we start write our switch case and that is you have to take in consideration that there are years that are leap years and that have one day more than the year that is not a leap year and there is a rule for that so I’m going to copy the rule that that is going to help us to determine whether a year is a leap year or not and that is this rule here so any year that one modulated by four gives the result of zero and at the same time that year modulated by 100 is not equal to zero or a year so that same year when modulated by 400 is going to give the result of zero and this here is going to be a definition for our leap year which means a year that has 366 days or a February inside this year has 29 days that’s why we need this rule here so now let’s write out our switch case statement and if you haven’t watched my video on switch case statement I am going to link it here one more time because you really need to understand the switch case and then you can come back to this video and deepen your knowledge on switch case so switch this is going to be the syntax of our switch case but I’m going to delete this default syntax we want to write it ourselves so inside these parentheses here I’m going to put the variable that we are going to switch through and that is going to be our month variable like this so whichever value our user has entered for our month we are going to cover all the potential values that our month can hold in our cases so the first case that I want to cover is going to be the most specific one and that is going to be our February which means second month so I’m going to say in the case that this month variable is equal to 2 which means that our user is requesting from us to determine how many days our February month has we really in this case need to check whether that year is a leap year or not and then if that year is a leap year that means that our February has 29 days and if not which means if this condition here is not true that means that our second month has 28 days so I’m going to copy this expression here this condition and also if you are not familiar with Turner operator you have to watch that video because in this video we are going to use that tary operator you can do it as well with if else statement but I want you to practice also this because you will uh you are going to actually come across it in your programming career so here I’m putting this condition for a leap here and I’m going to say this question mark and then I’m going to say if this here is true you have to write out this line of code so you have to write out C out and if this condition here is true that means that our year is a leap year which means that our February our second month has 29 days so let’s say 29 days month like this okay and so that is in the situation where this here is true and in the situation where this expression here results as false I’m going to put here a column sign and then I’m going to write out a different message and that is going to be that this second month in the case where a year is not a leap here has actually 28 days so after we have written this expression here so this Turner operator we have really write out how many written out how many days there is in our February month and after each case I have to put break so in this case as well I’m going to put put our break command after it and with this example with this case here we have really covered our second month which was the most specific one now we are left to cover the remaining months which means ones that have 31 days and also ones that have 30 days and here I’m going to show you something that I haven’t shown you before let me scroll this code like this maybe okay and then there are some months that contain 30 days and some that contain 30 31 days and the ones that contain 30 days are following so I’m going to write out case like this and then the the first month that contains 30 days is going to be April so fourth month and then also our sixth month contains 30 days and then also let’s see 4 6 9th and then November as well like this and here we have written out really all the months that contain 30 days okay and now I’m going to at the end so at this case here write out a message let me copy this and I’m going to paste it and I’m going to say 30 days month like this okay and I’m going to put break command here as well so let me explain this part of code here because we haven’t seen this part of code here before this break statement what it does is when your program so when your program execution actually comes to this case here it says okay my month is equal to two so I’m going to execute this part of code here and then it comes to this break command and this break command really breaks the execution of your switch which means that when your program comes to the first break command it is going to stop the execution of your switch there which means that it is not going to check any more cases and because of that you can really hear so you can put more than one month you can put all months that have 30 days like this and then you can write out the same message and put one break command at the end and how that is going to really behave inside your program in the case where user enters for example month six your program is going to check whether that month is is equal to two and it’s not going to be then it’s going to check whether your month is equal to four not as well and then it’s going to come here and say okay this is sixth month this that our user has entered so please execute whatever code you find until you come to the first break and that is going to be this here which is empty so nothing and then this here which is as well empty so nothing and then it comes to this code here and that line so this code here contains this see out message 30 days month so it is going to write out this and then it really comes to this first break command and it breaks your switch which means that it is not going to check any other cases that come after this break okay so in any case whether your user enters month four or 6 or 9 or 11 your program is going to execute this line here and then break your switch so with this part of code here we have really covered all months that have 30 days and now we are left to cover the ones that have 31 days and those are months uh let’s see that is our January and then our third month and our fifth and our 7eventh month like this let me scroll it a little bit more okay and then we have as well case 8 and case 10 and as well our December has 31 days so there are seven months that have 31 days uh five five months that have 30 days and one month that has 28 or 29 days and in this line here we are going to write out a message that is going to say 31 days month and as well here we have to put our Brak command like this okay so I am going to run my program now and show you how this program behaves so our program is asking us to enter a year and month let’s say a year is going to be 2020 which is current year and then a month is going to be let’s see it’s April so 4th and it says that it is a 30-day month which is April April has 30 days and let’s run our program one more time and let’s say 2020 again and let’s say that we want check our second month and it says that February of 2020 has 29 days which is correct as well and there is really one more situation that I want to cover and that is going to be a situation where our user enters a number that is not a valid month number and that situation I’m going to cover with my default statement so I’m going to write out default and in this default case as well I want to write out a message to my user like this and inside here I’m going to say not valid Val which means that our user has not entered a valid month number so let’s run our program and if I enter year 2020 and for a month let’s say minus 5 for example you see that our program has written out not valid okay so I hope that you have liked this video and if you did make sure to subscribe to my channel and share it with anyone who would like to learn programming as well and today is May the 2nd that’s when I’m filming this video I don’t know when I’m going to publish it probably in a couple of days and currently we are a little bit over 900 people so let’s see how fast this channel can grow thanks for watching and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners and in this video I wanted to talk about loops more specifically about while loops Loop so what are Loops what are they used for how they are used well Loops are used when you want to execute a block of your code multiple times while a certain condition is true which means you give a certain condition to your Loop and you say you are going to execute this block of code while this condition here is true so however many times it is necessary and one thing that I want to mention before we start uh on our example is the following so selection sequencing and iteration those three are three main building blocks of programming languages and when you really learn and understand those three you should be able to solve any logical programming problem and in this video we are going to talk about iteration we have already talked about sequencing and selection in my previous videos so what is sequencing well that means that your code is executed sequentially which means one line after the other and then selection that would be really when you want to select one part of the code rather than the another one which means you are going to tell to your program under a certain certain situation it really has to select which block of code it is going to execute the same would be when you for example come to a crossroad and then you have multiple ways in front of you but you really have to select which one you are going to take because you cannot take all of them and then iteration is going to be really iterating or executing multiple times a certain block of code certain part of code while a certain condition is true so while a certain condition is fulfilled you are going to execute the same block of code so let’s see our example now so I’m going to paste the text of my program here and this is our task so it says that we have to write out all the numbers between 100 and 500 that are divisible by three and by five and how we are going to do that first I want to explain you the algorithm so how we are going to solve this problem and then we are going to translate that algorithm into our code so this interval here so this 100 to 500 interval we are really going to iterate through all of the numbers of of this interval and we are going to do that using while loop and then for each of those numbers so for each value of our counter we are going to check whether that counter value can be divided by three and by five and if yes we will write out that value if no we are just going to continue to the next iteration so as I already said we are going to use while loop to solve this problem and and we are going to start our V loop with the counter value of 100 and in each iteration we are going to really increase the value of our counter so 101 102 and three and we are going to stop the execution of our V Loop when this counter value comes from 100 to 500 And1 which means 500 value of counter is going to be our last iteration through our Loop so so the first thing that I’m going to do is I’m going to really declare a variable that is going to hold our current counter value so I’m going to call it int counter like this and initially I’m going to set the value of my counter to 100 okay so this is our initial value of our counter and then let’s see what is the syntax of of our while loop so so we write out while like this and then in these parentheses we are going to put our condition so how long our Loop is going to execute and then in these braces here so in this curly brackets we are going to put which block of code our while loop is going to execute while this condition here is fulfilled and let’s now fill these parentheses here so as I’ve said our counter has to go from 100 to 500 which means since it starts on 100 here we have to say to our while loop that the execution of this block of code here really has to stop when our counter comes to 500 or 5001 500 is still valid value so that we are going to say like this so we are going to say counter like this and then we are going to say there are two ways to write this condition the first one is to say while our counter is less or equal to 500 or you could as well said while our counter is less than 51 so that is a valid situation while you’re executing your Loop so while your counter is less than 501 or while your counter is less or equal to 500 I prefer it this way but whichever way you put it is going to work so now that we have put this condition here we really can write out this code that comes in this while loop block so what we are going to execute while this condition here is true and that is going to be following inside this block of code here we really have to check whether our current value of our counter is divisible by three and by five and if it is we have to write out that number to our user if no we just need to continue to our next iteration of our Loop and how we can check whether this counter value can be divided by three and by five well we use modulo operation for that if you haven’t watched my video on operators I’m going to link it here make sure to watch it and here we really put the following so we can say if and also if you’re not familiar with if statement going to link it here so if our counter value so our current value of our counter after you modulate it with three if the result of that is zero that means that our number so our counter is divisible by three and we also have to check whether our counter is divisible by five as well we use this modul operation here and we say whether our counter modulated by five is going to equal to zero and if this condition here is fulfilled we really have checked this part of our task and if this part here is true we have to write out that number so in this situation here I’m going to say C out like this and I’m going to put inside here let’s see we are going to write out the value of our counter like this and we are going to write out is divisible like this and let’s put one end line after this line of code here because we are definitely going to have multiple lines so we want our lines to be formatted nicely okay so this part of code here has really covered this divisible by three and five and write out that number if it is divisible by three and by five five and there is really one very important thing that you have to keep in mind each time that you write loops and that is the following so you have to give your Loop away so that it can stop executing this block of code here so under a certain condition it really needs to leave this block of code here because if you don’t do that you are going to end up with an infinite Loop you are really going to lock your program in an infinite Loop situation and this code here this Loop here that we have written this is really an infinite Loop so let me prove that I’m going to run my program and as you can see the console is empty so I enter any value enter whatever it is not really reacting and why has that happened well your counter value starts with 100 and then it comes to your while loop and your while loop checks this condition here so it checks whether your 100 is less or equal to 500 and the answer to that is yes which means that your program execution can enter this block of code here so it can start executing your Loop and then it comes here and it says please check whether my counter which is 100 is divisible by three and the answer is no so this part of code here is not even going to be checked because of the nature of this end operator it really needs both of these operant to be true in order for this expression here to be true because this here is not true it’s false 100 is not divisible by three it is not even going to check this condition here and this line of code here is not ever going to be written so after that it comes here to this closed curly brace and then because of the nature of while loop when it comes here it really goes back here and then it checks again your value of your counter whether that is less or equal to 500 but nothing has changed your counter value is still 100 and then it is going to enter again here and then really repeat that process over and over again and your program because of that is going to be locked inside an infinite Loop so let me prove that really because here we have an empty console and you cannot see what is happening in the background so I’m going to stop my program and I’m going to write out here let’s write out C out like this and let’s write out infinite Loop and if I run my program now as you can see your program has really entered in an infinite Loop and it is writing out this infinite Loop text for infinite number of times so as you can see it says infinite Loop okay and this execution here is not really going to stop until your program’s memory is full and then it’s going to crash so whatever code in the case that you had some code here it is not ever going to be executed so I’m going to stop this here and I’m going to delete this part of code here because we don’t really need it what we need is we need to put here a certain code that is going to help our Loop to really stop the execution at a certain point and the code that we need to put here is going to be really following it’s going to be counter plus plus like this what this code of here this code here is going to do in each iteration it is going to check whether this condition here is true if yes it is going to write out this part of code here and then in each iteration it is going to really increase the value of your counter by 1 which means in your first iteration is going to be 100 after that it’s going to be 101 102 103 and it is going to really go until it comes to 500 that is going to be the last iteration of your program and then when it comes to 5501 this condition here is not going to be true anymore and then your Loop is going to check really whether 51 is less or equal to 500 and the the answer to that is not going to be no so your program is going to really stop the execution of this Loop and come here and then really stop your program so if I run the program now I’m going to prove that okay so this has been executed very fast and as you can see this is the result of your program it has really written out all the numbers that are divisible by three and by five and you can check check all of these numbers using your calculator if you want so with this expression here with this counter Plus+ we have really both iterated through all the numbers between 100 and 500 because we check our counter value here and then also we have we have really given a way to our Loop to stop the execution of this block of code here when this counter value comes to 51 and this is the result of our program okay so I hope that you have liked this video any questions that you have write those in the comments down below and I’m going to answer those make sure to subscribe to my channel and share it with all your friends anyone who would like to learn programming and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners today I want to talk about while loop and I have already made one video on this topic and if you haven’t watched that I’m going to link it here so make sure to do so and why I’m making this video because I really believe that watching One video and doing only one example is not going to be enough for you to really Master a certain concept it wasn’t for me it is not going to be for you as well and that is completely okay so we are going to show you how this while loop is used on one more example and the program that I want to build today is going to be a program that has to count how many digits the number contains so our user is going to enter a number and then we are going to write a program that is going to count how many digits there are in that number so let me copy the text of that program like this and it says count digits of a number so let’s do do the first thing that we know that we have to do and that we know how to do as well so that is going to be write out a message to our user so that he enters that number and then also allow him to enter that number so I’m going to say see out and then I’m going to say number like this and then I’m going to allow my user to enter that number before I can enter it I have to really declare a variable that is going to hold that number so here I’m going to say int number like this and then here after we have written out this me message to our user we are going to say C in number like this so after our user has entered his number we really have stored it in our number variable and now we are going to write out the program that is going to count the number of digits of this number here so let’s first see one specific situation that can happen and that is going to be when our user enters number zero so this number holds a value of zero and in that situation I’m just going to write out a condition so I’m going to say if my number like this is equal to zero in that situation situation please just write out a message to my user like this you have entered zero okay like this and I don’t need semicolon here this looks better so this here is a situation where our user has entered number zero and in that case we just want to write out that he has entered zero and now we are left with the main problem of this task and that is to count the digits of the number that our user has entered and that part I’m going to put in my else block like this and if you’re are not fam familiar with if else statements make sure to watch that video it’s going to be linked here so here in this else block I want to write the program that is going to count the digits of a number which is not zero definitely because if we come here then our number is definitely not zero so how we are going to do that well let me show you the algorithm on an example let’s say that our user is going to enter a number 1325 for example that is the number that our user enters so how we are going to count the digits of this number well first we are going to have a variable that is going to be called counter like this and initially we are going to set the value of that counter to zero so that is initial count of our digits of number and then we are going to to use while loop to iterate through all the digits of this number and in each iteration we are going to do following so we are going to come here and then we are going to say okay take this last digit of my number and really remove it I don’t need it and as well increase the number that my counter is holding so increase the number of digits because we have removed one digit and then in the next iteration we are coming here and we are as well saying okay so take that last digit and increase my counter like this and then in the next iteration take the last digit increase counter and in the next as well take last digit increase counter and then when we come next time we really have nothing more to count so there are no more digits left our number at this situation here is going to be equal to zero and then we are going to know that there is nothing else to count and then we are really going to leave our Wild Loop and we are going to write out the value that our counter variable is holding which is at this situation for so let me show you how we how we can do that in our code so I’m going to delete this part here we don’t need it anymore and then here I’m going to write out the following so as we explained already first thing that we need to do is we need to create a variable that is going to be called counter like this or digits counter however you prefer and and that variable I’m going to assign a value of zero initially and after we have created this variable here now we need our while loop so while like this and then inside these parentheses here we really write out a condition that our while loop is going to check each time that it wants to run each time that it wants to iterate and that condition here is really going to be please check whether my number number is greater than zero okay so in any case where our number is greater than zero our while loop is going to execute this block of code that I put inside these parentheses and what we are going to put inside these parentheses well as we already explained previously first thing that we need to do is we need to say number is equal to number divided by 10 and what this line of code is going to do well let me show you that on an example let’s say that our number so our number holds the value of 1 2 3 like this and this line here really says the following it says Please do this expression here so calculate it and whatever this expression here results in assign that to my number variable and 1 2 3 so 1233 divide by 10 because this here is whole number so it’s integer and this here is whole number as well the result is going to be whole number and that is going to be 12 or 12.3 but but because result has to be the whole number that3 part is just deleted bye-bye so then this 12 in this situation is going to be assigned to our number variable okay so that means that this number divided by 10 is really going to take away that last digit which we have previously explained so I’m going to delete this part here okay and this line of code there is really one more way to write this so write the same thing so I’m going to comment this here and I’m going to write out number divided equal so number R like this 10 okay so this line of code here and this line of code here are exactly the same this is just shorter way to write this here and this looks prettier to me but you can leave whichever of these two you prefer okay so after we have taken the last digit from our number what we are left to do is to increase our counter variable by one so we can do that using our increment operator here so this part of code has really in each iteration taken away one digit and then increased counter variable so what we should do now after our while loop finishes we should really write out how many number how many digits our number contained so we are going to write out count number contains like this and then let’s write out the value that our counter variable is holding like this what is this oh it says count instead of C out okay and then let’s write out just digits like this okay so our number contains whatever our counter variable is holding digits so now I can really run my program and let’s do that so it asks us to enter a number let’s enter number 1 2 3 for example and it says that our number contains three digits which is correct so let’s very quickly explain one more time how this has happened so I’m going to stop my program and I’m going to say here that our user has entered number let’s say 1 2 3 so our program in this situation comes here to our while loop and it says please check whether the number that our user has entered is greater than zero and that number is 1 2 3 so 123 which is greater than zero so then our program can really start executing this wild Loop so it enters here and then it comes to the first line of this while loop and it says Please do this expression here and this expression here really just takes the last digit of our number away and that is going to be three so we are going going to take that away and then the next thing that needs to happen is increase the value of our counter since previously the value of our counter was Zero now the value is going to be increased by one so that is going to be one and after that our program comes here and because of the nature of the while loop it goes back here it checks again whether our number is greater than zero our number is 12 now so the one digit has been taken away so that is still greater than zero so then our number really comes here and then does does this line of code again so it says again please take away one digit from my number so then it takes away this two part and then it comes here it says now increase my counter because you have taken away one digit and that is going to be two now after that our program comes here and then goes back here checks whether our number so whether our one is greater than zero it says yes and then it comes here and it says says please divide my number by 10 so take away that one digit so that one digit is taken away and we are left with zero and then our counter is increased by one and then we are really going to come here again and then our program goes back and says please check whether my number so whether zero is greater than zero and then our program says no it is not so our while loop is not executed anymore and then it comes here instead dad and it writes out that our number contains three digits and there is one more situation that I want to show you and that is going to be what is going to happen in a situation where our user decides to enter a negative number so let’s run our program and let’s see how our program is going to behave in that situation so now I’m going to enter a number of Min – 335 for example and you see that our program writes out that our number contains zero digits why has that happened because our program has come here so it has increased our counter it has actually assigned our counter a value of zero and then it has come here and it is it has really tried to check whether our number is greater than zero but because our number is minus 335 that is not greater than zero so our program then really is not going to execute this block here but it’s just going to go here directly so then it’s going to write out that our number contains and the value that it has assigned to our counter here which is zero so our number contains zero digits and that’s the message that you see here so that is the explanation of this behavior and we need to solve that now how we are going to solve that well it’s pretty simple so here when we come to this else Block in this situation in this 14th line of code we are really sure that our number is not equal to zero because we have checked that here but here we really don’t know whether our number is less than zero or greater than than zero so here we really have to check whether our number is less than zero and if it is we really need to get the absolute value of our number which means if it is negative we have to convert it to the positive number so here I’m going to write out the following condition so I’m going to say please check if my my number is less than zero like this and then if this here results as true I’m going to write out here a way for my program to convert this number in case that it is negative into a positive number and how we can do that well we can really multiply that number by minus one so we can say number is equal to -1 * number like this okay so now if I run my program and if I enter value of Min – 236 for example our program now writes out that our number contains three three digits which is correct so how has this happened our program has come here it has really checked that our number is less than zero and then it has come here and it has said please do this expression here and then assign that to my number so -1 * 2 – 236 those minuses are going to really convert into plus sign and then 1 * 236 is going to be 236 and after that we are going to do the same logic here so we are going to write out that our program that our number contains three digits which is correct answer okay so that is the one situation that I wanted to explain and there is also another situation that I want to explain to you and that is what is going to happen in the following situation here so let’s see let me enter a number that is very very very large I I cannot even read this number here so how our programs going to behave in that in this situation here write that in the comments down below please before I execute this here and now if I press enter what is going to happen happen well our program has glitched a little bit and after that it has written out that our number contains 10 digits but this is definitely more than 10 why has this happened if you are not familiar with data types and overflow and concept Concepts that I have already talked about in one of my videos I am going to link that video here so make sure to watch that video and now I’m very quickly going to explain what has happened here but make sure to watch that video so when we have entered this number here let me stop this program and let me put let’s see let me put a breakpoint here and now I’m going to run my program and what this breakpoint is going to do it’s really going to stop the execution of my program at this line here and we haven’t talked about breakpoints or debugging programs previously but if you want me to include that in one of my next videos make sure to write that in the comments down below because I really believe that it is important for you to see how your program is executed line by line so to be able to follow it and in that way you can really discover any bugs and any situations that are tricky and that are happening inside your program so you can see and control that better so I have put here a break point and let’s now enter a number that is going to be a very large number okay so if I press enter now you see that my program has really stopped the execution here on this line here so after I have entered my number and then even though I have entered a number that is pretty large let’s hover over this number variable you can see that it is holding a value of 2 billion And1 147 million and something so this value here is definitely not equal to this value here but because our program has really gotten the value that is much larger than the maximum value that our int variable can hold it has really assigned the maximum amount that our int can hold to our number variable so that is what has happened in this program and if I click continue now you can see that our program writes out that our number contains 10 digits because it really was holding a 10 digigit number so that is the maximum amount that our int type can hold okay so that is the last situation that I wanted to explain to you and I hope that you like this video and if you have learned something new make sure to subscribe to my channel share it with all your friends anyone who would like to learn programming thanks for watching and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners and first things first make sure to subscribe to my channel and hit that Bell icon as well and share this video with everyone it really helps me to reach a lot more people and in this video I want to show you how you can reverse a number so your user is going to enter a number and what we want to do is we want to write out that number in Reverse so reverse the order of the digits of that number and here I have opened my visual studio so let’s copy the text of this task like this and the first thing that we need to do is we need to really create a variable so let’s say int number like this so that our user can enter his value in this variable here so let’s write out a message to our user so let’s say see out number like this so that our user knows that he should enter a number and then let’s accept that value in our number variable oh number like this now after our user has entered a number let’s really think about how we are going to solve this problem okay I get it so the first thing that I notice here is that we are missing a variable and that variable is going to be the one that is going to hold our reversed number so let’s declare it here I’m going to add it here and I’m going to call it let’s say reversed number like this and I’m initially going to assign it a value of zero okay and now the algorithm that we are going to use in order to solve this task in order to reverse our number so the algorithm that we are going to use is going to be the following so this reverse number here it is holding a value of zero initially and this number here is the one that our user enters so let’s say for example that our user enters a value of 123 like this so 1 23 so how we are going to reverse this number here the algorithm is going to be following so we are going to iterate through this number here so all the digits of this number here we are going to go through those and in each iteration we are going to do the following so the first thing is we are going to say please take this reverse number and multiply it by 10 so 0 * 10 is going to say to stay zero after that what we are going to do is we are going to take this last digit of our number that our user has entered and we are going to add that number to our reverse number so 0 + 3 and that is going to be equal to three and after that we are going to really remove that last digit of our number so I’m going to delete that digit and then in our next iteration what we are going to do is the same thing so we are taking this reverse number we are going to multiply it by 10 so I’m going to say 3 * 10 that is going to be equal to 30 and after that we are going to take this last digit of our number and we are going to add that digit to this number here so to this reversed number so 30 + 2 that is going to be equal to 32 and then we can really remove this last digit here so I’m going to deleted after that we are going to the to the third iteration and we are doing the same thing so we are taking this revers number multiplying it by 10 so 32 * 10 is going to be equal to 320 and then we are taking the last digit of our number this is this one here and we have to add that digit to our reversed number so 320 + 1 is going to be equal to 321 and after that as we did before we can really delete remove this digit here and then in my next iteration we are going to come here again and our Loop is really going to see that there is nothing else left to iterate through so there are no more digits and then it is really going to leave that Loop and at that moment we are really going to have our reverse number so 3 2 1 that is reverse number from the one that our user has initially entered so let’s now translate this algorithm into our code so the loop that we are going to use in order to solve this problem here is going to be while loop so I’m going to write while and then in these parentheses here I’m going to really give it an expression that is going to check each time that it wants to run an iteration and what we are going to iterate through are the digits of this number here so the number that our user has entered so I’m going to say please iterate through this part here so execute this block of code here which is currently empty while our number so number where is it is different than zero like this okay and inside here we are going to write out the algorithm that I just explained and the first step of that algorithm was really multiplying our reverse number by 10 so I’m going to say reverse number is equal to reverse number time 10 like this okay and the shorter way to write this expression here is going to be like this so you can really take this part here delete it and say it like this it is going to do absolutely the same thing so it is going to really multiply our reversed number by 10 and then whatever that results in it is going to assign that back to our reversed number so that was the first step the Second Step In order to reverse our number is going to be really to take the last digit of this number that our user has entered so how can we do that we can do that by modulating this number here by 10 so I’m going to declare a variable let’s call it um last digit like this and as we already said we can get that last digit if we modulate this number here where is it so this number that our user has entered by 10 okay that is going to give us the last digit of this number here and then what we really want to do is we really want to add that last digit to our reversed number that was one part of this algorithm so the next step so I’m going to say reversed number plus equal to last digit like this or you can write it a longer way but this way I pref I prefer to write it um this way but you can as well say reverse number is equal to reverse number plus last digit and after we have added that last digit to our reverse number there is one more step left to do and that is to really take that last digit from our number and how we can do that well we can really do that by dividing our number by 10 so you can say number is equal to number divided by 10 or number divided equal to 10 whichever way you prefer okay so this is really the algorithm that we explained and this step here you can can really write out the shorter way if you want so you can say for example reverse number plus equal to number modulated by 10 like this so you can make your code a bit more readable if you prefer it this way or you can leave this part here and then really add your last digit to your reversed number so now that we have done this algorithm here let’s write out our reverse number and see what we have done so I’m going to write out C out and I’m going to say reversed like this okay and I’m going to write out our reversed number okay let me delete these empty spaces and if I run my program now it asks us to enter a number so let’s enter number 1 2 3 and now if I press enter you can see that our program has really reversed this number here so let’s quickly one more time explain how this has happened so our while loop has really iterated through this number here so that in each iteration it is going to do the following so it is going to take our reverse number and initially that reverse number is equal to zero so it is going to multiply that by 10 so it stays zero and after that is going to take that reverse number and add it the last digit of our number that our user has entered so that is going to be in a first iteration number three so our reverse number in that case becomes three so 0 + 3 is equal to three and after that we are going to really take that last digit from our number that our user has entered so it has taken this three part away and then in the second iteration is coming here it is going to check again whether or not number is not equal to zero and our number is going to be 12 in that situation so that is not equal to zero so it enters here again it executes this block of code here so it says again please multiply my reverse number by 10 and assign that again to my reverse number so our reverse number was three and if you multiply by 10 if you multiply 3 by 10 you are going to get 30 after that it is taking the last digit of the number that our user has entered which is two now because three we have taken away in our previous iteration so it is going to add that two to my reversed number so number reverse number is going to become 32 now and then it is really going to take that last digit from our number away it is going to divide it by 10 so now we are left with number one and our reverse number is equal to 32 and then it goes back to to our third iteration it checks again whether our number so whether our remaining number is equal to zero and this one here is the value of our number so that is not equal to zero so this condition here is fulfilled it can enter the while loop so it does this algorithm here again so it says please multiply my reverse number by 10 our reverse number at this point is 32 so when you multiply that by 10 you get 320 and then after that it takes the last digit of our number which is going to be this one so this one here which is the last one remaining so it is going to take this one and add it to my reverse number as you can see here and then it is really going to take that last digit away so it is going to take all of these three digits away so it has taken them in a previous situations and now it has taken this one away as well so our number is equal to zero now now and then it goes back to our fourth iteration it checks whether our number is not equal to zero but in this situation our number is equal to zero so it really leaves this Loop here so it is not going to enter in this Loop anymore and then it goes here and it really writes out the value of our reversed number which is this line of code here so that is how we have reversed our number so I hope that you like this video and that you understand this explanation if you have any questions write those in the comments down below and also share this video with all your friends with anyone who would like to learn programming and thanks for watching I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners if you are already a subscriber welcome back and if you’re a new viewer make sure to subscribe hit that Bell icon as well and welcome to my channel so in this video I want to talk about the while loop and in my previous videos we have already talked about while loop and iteration in general so if you are not familiar with those make sure to watch that video I’m going to link it here but in this video I want to explain to you how and when is used do while loop and I’m going to give you an example of a program that is usually used and for example applications such as when you try to unlock your phone and then you are given three attempts to guess your pen and if you guess it correctly then you can proceed loading your phone’s applications further or for example if you want to unlock your credit card so you put your credit card in ATM and then it gives you three attempts to unlock your credit card if you guess your pen correctly you can proceed further but if you fail so if you don’t guess your pen correctly in those three attempts your account gets blocked so that is the application that we are going to make today and for that we are going to use do while loop so there are three things that we need actually three variables so I’m going to declare those three here the first one is going to be our let’s say the the pin of our user so let’s call it users pin like this which is going to be really the correct pin the one that you want to guess so I’m going to put here let’s say 1 2 3 4 that is going to be our user pin after that that we need another variable which is going to be really the pin that our user enters so let’s call that variable just pin okay like this and then the third variable that we need is going to be really counter of our errors so the counter of the attempts and errors that our user has made so I’m going to call that variable error counter like this and let’s set that value initially to zero okay and the next thing that we need to do is we really need to give our user three attempts in order to guess this pin here and if he guesses it correctly in those three attempts we are going to write out that the application can be loaded further so we are going to write out application is loading or something like that but in the case that our user does not guess this pin here so this pin here correctly we we are going to really write out that the application or a credit card whatever has been blocked and how we are going to do that so we are going to use do while loop so I’m going to write out do like this and then here I’m going to put while because that is the syntax of our do while loop okay and here you need semic colum because if you don’t put it you are going to get a syntax error now here we put the block of code that we want to execute in each iteration and here we put the condition that we want to check each time that this code here is executed we come here and then we check that condition and if this condition here that we put is correct we are going to go again here and do one more iteration and then again check and then do more one more iteration and we are going to repeat that until this condition that we put here is no long longer true when it when this condition here when it becomes false we are going to leave our do while loop okay so what do we want to enter so what do we want actually to do in this block of code here we really want to write out a message to our user so that he knows that he should enter a pin a pin and then we want to really accept that pin that our user enters in this variable variable here so let’s do that first I’m going to write out C out like this and then then let’s just write out pin like this and let’s accept the value that our user has entered in our pin variable like this okay and then after we have done this what we need to do is we really need to check whether this pin here so this pin that our user has entered corresponds to this pin here so whether this value is equal to this value here and if they are not that means that our user has failed so in that case we are going to increase our errors counter so I’m going to put here if pin is not equal to users pin like this what we want to do is we want really increase our errors counter variable like this okay and this code here so we want to give the the attempt to user so that he can enter a pin and then we want to check whether that pin is correct three times or until this pin here and this pin here are the same so until they are equal or until until our user has used all of these three attempts that we have given to him okay so here I’m going to really put that condition so here inside these parentheses I’m going to write out please do this block of code here here while our e let’s say while our errors counter is less than three like this and then also at the same time while our pin is not equal to users pin like this which means that this block of code here is going to be executed while our user has not used all of these three attempts that we have given to him and while this pin here so this pin here and this pin here are not equal in a situation where this here results as false we are going to come here and after that when we come here we really want to check whether we have left this do while loop here because our errors counter has reached three or because these two were the same in a situation where our errors counter has reached three that means that our user has used three attempts and that he has not guessed his pin correctly so I’m going to put here if our errors counter is less than three like this and this condition here really means that this do while loop has been left in a situation where our user has not used all of these three attempt that we have given to him that means that this while condition has really failed on this part here so that means that our user has entered 1 2 3 4 as pin and in that situation 1 2 3 4 is not equal to 1 2 3 4 that results as false so this whole expression here this whole condition results in false as false and then we leave our do while loop and in that situation if our user has not used all of these three attempts that really means that he has guessed his pin correctly so here in this if situation we can write out to our user see out you have guessed or you can proceed with loading of of this application so I’m going to write out just loading like this but in a situation where our while loop has been left because this errors counter is greater than three actually it is going to be equal to three that means that our user has failed in guessing his pin three times and that means probably that he’s not trying to unlock his phone or his credit card so in that situation we are really going to block that account so we can say else see out blocked like this okay and I’m going to put one more here like this so this is going going to be a program that we really use to allow our user to enter three attempts of his pin and in a situation where he guesses that pin correctly in those three attempts we are going to write out to our user that he has successfully unlocked his phone for example and we can proceed with loading of applications but in a situation where he really uses all of those three attempts and fails to guess his pin we can write out that the application is blocked oh blocked now now it’s now it’s okay so let me run this program and let’s try to use three attempts so I’m going to say that my first attempt is going to be for example 1 one one one like this so it says you have not guessed correctly please enter pin again this is what it means after that I’m going to try for example 2222 it tries to prompt me to enter my pin again because I have failed previously and let’s say that my third third attempt is going to be 3333 like this and then it has said it has written out a message that my account has been blocked because I have missed three times okay so that is one scenario and and the other scenario is going to be really where we guess the one where we guess our pin correctly so let’s say that our first attempt is going to be um 111 one again and after that we really remember what is the correct pin and we enter 1 2 3 4 like this and then if I press enter it says really you are loading you can you can load your application now or the further loading of your application is going to begin now because we have T the correct pin so let me very quickly explain one more time how has this happened so this code here when we come to this do while loop the first thing that is executed is this line here so it says please enter your PIN and then after your user enters the pin your program really checks whether that pin is equal to user’s pin so the previous pin the one that he needs to guess and if those two are not equal that means that your user has not guessed correctly and then you want to increase your errors counter so the number of attempts that your user has used and failed actually in using so we increase in our first iteration that errors counter to one so from 0o to one and then we come here and then our Loop really checks whether that errors counter is less than three so one is less than three that is true and also it checks whether that pin here is is not equal to the pin that we need to guess and in this situation it is not equal so it also this this whole expression results as true and it now can go here again so it prompts you again to enter the pin so you can enter the pin now and in this situation we enter 2222 for example and then it guesses it it checks again so it checks whether pin that you have entered so 2222 is not equal to 1 2 3 4 for those two are not equal so it increases the errors counter once more and it becomes two now then you go here and then it says okay please check whether my user has used all of these three attempts it it it says that your errors counter is still less than three so you have used only two attempts so far and then this condition here results as true because you have entered 2222 and that is not equal to your PIN so 1 2 3 4 and then it goes back here tries to prompt you one more time to enter your PIN and then if you fail this time it increases your errors counter to three like this and then it goes here and it checks whether your errors counter is less than three your error errors counter in this situation is uh has become three so this condition here results as false and your while the while loop actually is now broken so you are not going to continue the execution of your do while loop but you come here and then it checks whether errors counter is less than three because this here fails because this here results as false you are presented with this message here so blocked your phone your account has been blocked okay and in a situation where your user guesses correctly that errors counter is going to be less than three and you are going to be presented with a message of loading and there is one important thing that I want to mention and is really the difference between while loop and do while loop in do while loop you first do so you first execute this block of code here and then you check the condition and then if that condition results as true you go back and you again do this block of code here and then you check and then you do but in a situation of while loop you first check the condition and then if that condition results as true then you can really proceed with executing your block of code that comes after your while but in this situation here so in the situation of do while loop you first do this block of code here so uh irrelevant whether this condition here is true or not you are going to do this block of code here at least once I hope that you like this video if you did make sure to subscribe to my channel and click that Bell icon as well and also if you want me to post more videos like this make sure to like this video because then I will know that you liked it and well that’s all I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners in this video I want to talk about four Loops but before we start make sure to subscribe to my channel and hit that Bell icon as well okay so what I’m going to explain today I want to explain to you how for Loop works and I’m going to explain that on a simple example which is calculating the factorial of a number so let me copy the text of our task here like this and I’m going to comment it out so what is the factorial of a number factorial of a number is usually defined as a product of all numbers between one and that number that you want to calculate the factorial of that means for example if your user enter here is number six let’s say and you want to calculate the factorial of number six you are going to do that in a following way so 1 * by 2 multipli by 3 4 5 and oh sorry six okay and then this here is going to result in 720 so this 720 is really going to be the result of your factorial of six and this example here is what we want to really translate in our program so we want our user to enter a number and then we want to calculate the factorial of that number and write that result out to our user and we are going to use for Loop for that so let me quickly declare a variable which is going to be called number okay like this and let’s prompt our user that he should enter a number and then let’s really store that number that our user enters in our number variable okay so after we have acquired a number that we want to calculate our factorial of let’s explain how we are going to really do that so I’m going to do that using for Loop and what is the difference between four Loop and while loop and do while loop because we have previously talked about while loop and do while loop as well you can find those videos on my channel if you’re interested and I’m going to link those videos in the description of this video if you want to watch them so the difference is that usually when you use for Loop beforehand you should know how many iterations that Loop is going to make so for how long your Loop is going to run so let me show you the syntax of our for Loop you say four and then you use these parentheses here in which we are going to put certain expressions in a moment and after that you put these curly brackets in which we are going to write out the code that is going to be executed in each iteration of our four Loop so inside this parentheses here we need to put three things what are those three things the first one is going to be to set the initial value of our counter variable that is the first one after that the second is going to be to really put the condition that your for Loop is going to check each time that it wants to run this block of code here so before each iteration it is going to check that condition so that is going to be the second thing and after that the third thing is going to be really a way for your counter value to come to that condition condition which means that you have to either increase or decrease your counter variable in order to reach that condition at certain point and then when that condition results as false your for Loop is not going to be executed anymore okay so those are three things that we need to put in these parentheses here and let’s now look at this example here because from here we are going to really uh deduct which conditions which Expressions we are going to put here so if you notice this algorithm here because this is really algorithm nothing else um you see that this is really a counter this behaves as counter so it goes 1 2 3 four and it really starts at one and then it goes up to that value that your user has entered so we can use that for our expression here the first expression is initial value of our counter we need to declare that variable and we are going to call that variable I you can call it count or whatever you want really uh your compiler is not going to give you an error because of that but a common practice is to use a single letter variable name for this counter that you use in your for Loop so I’m going to use name I for that and the initial value of my I counter is going to be one because as you can see here it really starts on one and then after that we need to put the condition that your for Loop is going to check each time that it wants to run a new iteration and that condition as you can see here is really this this expression here this algorithm runs until it comes to this six until it comes to the value that your user has entered so we are going to put that here we are going to say please run this block of code here until my I is less or equal to number like this so whichever number our user enters and then the third thing is going to re be really to give our Loop a way to reach this condition here at some point which means to make this condition here false and then leave our four Loop and again we look here and you can see that your counter is really increasing in each iteration by one okay so here we are going to put I ++ which is in each iteration going to increase the value of our I counter by one okay so after we have put these expressions in these parentheses of our for Loop we need to really put a block of code that is going to be executed in each iteration of our four Loop and I’m going to declare before this for Loop here I’m going to declare another variable which I’m going to call tutorial and I’m going to give it a type of int okay like this and I’m going to assign the initial value to my factorial factorial variable and that is going to be one and then how I’m going to use this factorial variable in each iteration of my four loop I want to say that my factorial is going to be equal to whatever my factorial was previously holding multiply that by my current I value which means by the current value of my counter and how this is going to behave so let’s say that our user enters for example number three and then your execution comes here and it says please declare a a variable which is going to be called factorial and it is going to have a value of one so we have assigned that value here and then it comes to your four Loop the first thing that your four Loop is going to do is it is going to declare this I variable here and assign it a value of one so we we are going to write that here so we are going to say I is equal to 1 and then it really goes here and checks this condition here before it determines whether it’s going to run this block of code here or not so if this here results is true it is going to run this block of codee here and if not it is going to leave your for Loop so is your I less or equal to the number that your user has entered so your I is going to be one and then that is less or equal to three so your for Loop is going to execute this block of code here which means that it is going to come here and say factorial multiplied by one which is going to be 1 multiplied by 1 and that is going to result as one and it is going to assign the result of this here to your factorial variable which is going to stay one after that your for Loop comes here and at this close bracket here it really goes here and it increases the value of your I and this increment operator is going to increase it by one so your I now becomes two and then after that it goes back here and checks this condition here so it says please check check whether my two is less or equal to the number that your user has entered so two is less or equal to three so it is going to run this block of code here again and then it is going to do following so it is going to say please multiply my factorial value so the previous value that my factorial was holding which is one by the current value of my I which is 1 * 2 that is going to result as 2 and that is going to be assigned to your factorial variable so we assign two here okay and then it goes back to these Clos brackets and then it goes here increases the value of your I again so your I now is three and then it really checks this condition here so whether three is less or equal to three the result of that is going to be yes so it is going to do this expression here again so so the current value of your factorial which is going to be two multiplied by the current value of your counter variable which is going to be three so 2 ultied by 3 that is going to be six and that is going to be assigned to your factorial variable after that it goes here and then it really increases again the value of your I variable so of the counter that you are using in your for Loop and that value becomes four now after that it is going to try to check this expression here so this condition here and four is not less or equal to three so your for Loop is not going to execute anymore and then your really your your execution comes here and at this line of code here it has the value of six in your factorial variable which means that we are left only with the need to write out this to our user so we need need to say um let’s say it like this number okay and then let’s say factorial of that number is going to be equal two and then let’s write out the result so the result we are holding in our factorial variable like this so This should really write out the result of this here so the the factorial of this number that our user has has entered and if I run my program you can see that it asks us to enter a number I’m going to say let’s say for example three and then if I press enter it is going to give us the result of six which is the correct result the one that we previously got let’s run it one more time just check this number here so I’m going to say please give me a factorial of six and it calculates that the factorial of 6 is 720 as we did before so this is going to be really one way of writing this for Loop for this current example so for calculating factorial I want to show you another way how you can do exactly the same thing so I’m going to really comment this part of code here so I’m going to say um comment this block of code here and then there is another way to write these parenthesis here so as you can see this example here is what we have used in order to write these Expressions inside these parentheses but there is really one more way to calculate your factorial and that is going to be to start at this maximum value which means 6 factorial is equal to 6 multiplied by 5 by 4 3 2 1 and and that is going to be equal to 720 so now you start your counter at this maximum value so this number that your user has entered and then you really decrease the value of your counter and you go until your counter value comes to one and that is the condition when you stop so your one value of a counter is going to be the last iteration through your for Loop so now we are going to write out um so actually we are going to really write our for Loop using this algorithm here so we are going to say four and then also put this these parentheses which we are going to use for the block of code that we want to run through in each iteration and in these parentheses here I’m going to set the initial value of my counter that is going to be I is equal to and as you can see here our I starts at six so I’m going to put here six which means a number that our user has entered in this current situation it is six but since we want to calculate the factorial of whichever number our user decides to enter I’m going to use that variable here okay and then the condition that your for Loop is going to check each time that it wants to make a new iteration and that is going to be please run this block of code here until my I is greater than or equal to 2 1 okay and then the last thing that we need to put here is going to be really a way for our for Loop to stop at a certain point and if you look at this example here you see that your counter is decreasing by one in each iteration so we are going to put that here we are going to say I minus minus which means use this decrement operator on our I variable and then we are going to really use the same expression here here okay and this is going to give us the exact exactly the same result as this code here did so if I run my program you can see that it asks number again so if I enter number six for example it is going to give us 720 as this code here did as well so let’s repeat one more time there are three things that you need to put in these parentheses here in order to set up your four Loop and the first one of those three is going to be to set the initial value of your I variable which means the initial value of your counter after that you need to put the condition which is going to be checked each time that your for loop wants to run an iteration and if this condition here results as true your for Loop is going to run this block of code here but if this condition here results as false your for Loop is not going to run this block of code here but you are really going to leave your for Loop and come to the next line after it and then the third thing that you need to put in these parentheses here is going to be really to either increase or decrease value of your counter variable so that it can reach this condition here at certain point and make it false so we have decreased it in this example here and we have increased it in this example here so those are three things that you need to put inside these parentheses here and you really need to separate those three using this semic colum sign okay and there is one more thing that I need to mention and that is going to be really you can upgrade this program here so that it checks whether this number here is greater than zero because you cannot calculate factorial of negative number so our program is not going to be behave as expected if you enter negative number and also the factorial of zero is going to be equal to 1 so you can put that code here and determine whether your user has entered positive or negative number and in case that your user has entered negative number make sure to write out appropriate message to your user so I think that is all if you like this video and if you learned something new make sure to subscribe to my channel and hit that Bell icon as well share it on your social media because it really helps me to reach a lot more people so that all of us can learn and upgrade our knowledge in programming and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners in this video I want to talk about nesting Loops in my previous videos we have talked about while loop do while loop and for Loop and now I want to show you the example on how you can really combine and Nest those Loops so if you haven’t watched my previous videos or you are not familiar with loops at all I recommend you to watch those I’m going to link those in the description of this video and also before we start make sure to subscribe to my channel and click that Bell icon as well so what are we going to do in this video I want to really show you how you can nest for Loop and do while loop and the example that I’m going to use to explain that is going to be following so I want my user which is going to be a student let’s say to enter three grades or more if you want we are going to use three for desk exam and I want to those grades I want those grades to be between 1 and five and then I want to write out the average grade so the average grade between those three that he has entered so let’s start building our program the first thing that I need to explain is since we are going to enter three grades that means that we are going to repeat that entering process three times and for that I’m going to use for Loop so I’m going to write four and then in these parentheses here I’m going to put my initial set setup of four Loop which is going to be the first thing is going to be initial value of our counter so I’m going to declare a counter which is going to be called I and initially I’m going to give it a value of zero that is the first thing the second thing that I need to put in these parentheses here is going to be the condition that our Loop checks each time that it wants to run a block of code which is going to be this block of code that we put inside these parentheses so that condition we put here and that condition is going to be while our I is less than three so we want to make three iterations in the first iteration our I has the value of zero in the second iteration it’s going to have the value of one and then in our third iteration it’s going to have the value of two so we have made three iterations after that it gets the value of three but this condition here is not going to be true anymore so then our for Loop is not going to be executed anymore so that is the second thing and then the third thing which we need is going to be really increasing that value of our counter in each iteration so after age iteration and I’m going to put here this increment on our I variable okay so in this block of code here we are going to repeat three times something so what is that something that is going to be really the process of our user entering the value for his grade and since we said that that grade needs to be between 1 and five I am going to use do while loop for that how well I’m going to write out do okay and then here I’m going to put while which is going to be the condition so here we prompt our you user to enter the grade and then we we say here you are going to have to enter that grade while that grade is less than 1 or greater than five so since we don’t have any variable that we are going to use to enter that grade I will have to declare it here so I’m going to say here int grade like this okay and then let’s prompt our user in this block here to enter his grade so I’m going to write out C out and let’s say enter grade and I am going to use the current value of my counter so that I can really say um which grade my user is entering so enter first grade second grade and third grade so I’m going to say I + 1 like this y + one well because our counter starts at zero and it wouldn’t make much sense to say to our user please enter grade zero so that is why I’m increasing this value of my I when I want to write out a message to my user okay like this so here I’m going to write out please enter a grade and after that I need to accept that grade that my user enters in my grade variable so I’m going to say C in grade like this and we are going to repeat this process here for a single grade while our user enters a grade that is less than one or grade is greater than 5 okay so our program is really going to prompt our user please enter grade one and then he enter six for example and then our program checks this condition here and says okay you have missed this part here so go back and then please enter grade one so first grade again okay so if I run my program now let’s just prove that very quickly so our program our program says now enter first grade so enter grade one and then let’s say that I enter nine for example it prompts me again to enter first grade because I have not obeyed this rule here this part here so I’m going to say this time for example five and then it says okay you have successfully entered first grade let’s now enter second grade so for that second grade let’s enter for example zero and then it prompts me again you have not entered correct value for grade two please enter it again and let’s say that this time I’m going to enter one and then it asks for third grade and let’s say that this time third grade is going to be three so our program now has successfully accepted this third grade and now our program is going to really uh finish its execution because we haven’t written anything else after this part here so there is something else that we need to write and since we want to calculate the average grade of our user what we are going to need is going to be really to sum all of these grades that our user enters so I am going to declare a variable which is going to really hold that sum of our users grades so I’m am going to put it here I’m going to call it sum and initially I’m going to assign it a value of zero and later I’m going to explain why so I have declared a variable that is going to be of type int and I have called it sum and assign it a value of zero so this sum here is going to each time that our user enters a grade and we really um we really check that that grade is valid grade after that we want our sum to hold whatever it was previously holding plus the value of our grade like this okay so why I have assigned a value of zero to my sum because zero is a neutral value when it comes to adding numbers you add zero to whichever number and then you get that same number and in a situation where we didn’t assign any value to our sum we would get really um an error so if I try to run my program now you see that it prompts me with an error and it says uninitialized local variable sum used because it does not have any value assigned to this variable here it is going to say really that it does not know how to add the value so the value of our grade to our sum so that is why we need to assign some value to our sum variable okay so and that value is going to be zero because zero is neutral when it comes to adding numbers okay so now I can really run my program and as you can see um that error has disappeared so I’m going to stop my program and let’s very quickly write out this sum that we have calculated here so I’m going to say see out and I’m going to write out sum like this sum is equal to and then let’s write out the value of our sum and let’s add end line like this so I am going to run my program once more it prompts me to enter first grade I’m going to say that my first first grade is going to be for example five and then my second grade is going to be for example six uhuh that’s an error so please enter your second grade again so I’m going to enter this time two let’s say and then for my third third grade let’s enter one for example and it says that the sum of my grade grades is equal to 8 which is correct so 1 + 2 + 5 that is going to equal to 8 so what we are left to do now we should only really divide our sum by the count of our grades which is three because we have hardcoded this value here to three so our user can enter only three grades you can really use a variable for this or you can part code it to any other value that you want and need so here after this line of code here what I need to do is following so I’m going to say C out out and then let’s say average is equal to let’s say average grade is equal to and let’s write out the result so that is going to be sum divided by three okay is it though so I’m going to run my program and let’s enter for example value two and then again value two and then let’s enter for example value four and then it says that average grade is equal to two which is not correct but why has this happened so as you can see here we have used two integer variables so our sum is integer value and then three is integer value as well so when you divide two integer values the result is also going to be integer value so in order to get a floating point a decimal point Point number you really need to convert one of these two into a float type so you can say either here you can say float so please convert my sum variable into float and then divide or you can put here this 0 Z or you can leave both of these whichever you prefer so I’m going to leave both of these like this so if I run my program once more it prompts me again to enter first first grade so I’m going to say that my first grade is equal to five and then my second grade is also five and then let’s say that the third grade of our user is going to be nine so our program prompts us again to enter the third grade because it needs to be in this interval here so I’m going to say now that uh the value of my third grade is going to be three which is correct value and after that as you can see it writes out that the sum of these three grades is 13 and then average grade is 4.33 333 so that was an example on how you can really combine and Nest Loops in order to solve complex problems and thanks for watching make sure to subscribe to my channel click the Bell icon also share it with anyone who would like to learn programming and I’m going to see you in my next video bye hi everyone welcome to to my channel welcome to another video of C++ for beginners in this video I want to talk about nesting four Loops so I want show you how you can solve more complex problems using nested for Loop but before we start please subscribe to my channel and click the Bell icon as well and also like this video so this example that we are going to do today is going to be really multiplication stable so I’m going to show you the example that I want to program so that would be this here and if you look at this multiplication table that we want to make you can really start to notice a pattern and what pattern I mean you see here this this first end in this first part of my multiplication table so in this first table as you can see this first end is one and it stays one in this table here after that you can look at this second table you see that this end is now two and then in my third table it has increased to three 4 five and it really increases so it increments by one and it goes up to 10 okay so that is the first operand so this first part of my multiplication after that we can look at this second operand and you can really notice that it increases in each iteration by one so it goes one two three four five up to 10 and then it does the same thing in this second table so it goes from 1 to 10 again and then the same in my third table fourth fifth and it really behaves the same in this 10th table as well so that is the pattern that I want you to notice so this first oper end can be really represented using one for Loop so let’s say that that is going to be outer for Loop and it is going to increase each time that my second upper end Counts from 1 to 10 and that second opont we can really represent using another for Loop which is going to be really inner for Loop so the program the algorithm for for solving this problem is going to go like this you have outer for Loop which is going to count from 1 2 3 4 up to 10 so it is going to count from 1 to 10 and then you are going to have inner for Loop which is also going to count from 1 to 10 but for each value of my counter of my outer loop okay so that means that my outer loop counter changes only after my inner loop has counted from 1 to 10 so let’s copy the text of our task here I’m going to say multiplication table and let’s comment that text out so as we said in order to solve this problem we are going to use nested for Loops so I’m going to add empty space here and then the first thing that I need is going to be my outer loop so I’m going to really set up my outer loop I’m going to say four and then we need to declare a counter which I’m going to call I so I’m going to say int I is equal to and then since our outer let me show you this image one more time since it goes from one to 10 I’m really going to set its initial value to one so I’m going to say I is equal to 1 and then I’m going to write the condition so how long this for Loop is going to run and that is going to be while this I is less than or equal to 10 like this and then each iteration it is going to increase by one so that is going to be i++ okay and then I’m going to put this block of code here that is going to be executed in each iteration of this for Loop so what we need to do in each iteration of our for Loop let’s look at our image one more time and as you can see it really says that in each iteration of this outer for Loop you need to count from 1 to 10 so in this iteration here some other counter really counts from 1 to 10 and then new iteration so our I is now two and then counter counts again from 1 to 10 and then three but also we have this inner counter that counts from 1 to 10 okay so let’s really write that code so that inner counter that counts from 1 to 10 for each value of our I we are going to represent with another for Loop and that is going to be really that nested or that inner for Loop so I’m going to write four and that inner counter I’m going to call J so I’m going to write int J and since our J also Counts from 1 to 10 I’m going to set its initial value to one and I’m also going to say please iterate through this for a loop while our J is less than or equal to 10 as well and then in each iteration please increase the value of J by one so do this increment operation and then in each iteration of our J Loop we are going to execute this block of code here so what we are going to do in this block of code here well let me look at that image once more and as you can see in each iteration of our J so this is one iteration of our J this is second third fourth fifth and then 10th iteration of our J after that we change our I counter value so we increment that and then our J starts again starts one more to count from 1 to 10 so in each of these iterations as you can see really we have to multiply our I value counter with our J value counter and write the result of that so I am going to write that here I am going to write C out like this and then let’s write out the value of our I counter like this and then let’s write out this this multiplication operation and then let’s write out J like this this is just for maing our text so I’m going to put this equal sign and then I really want to multiply those two counters like this and let’s also add one end line here so that our text is formatted nicely because we are going to have multiple multiple lines so with this we we have really covered this multiplication part and there is only one more thing left to do and that is to add one more end line because I really want to make separation between these so I want to make separation between these tables this is going to be one logical part after that this is going to be another then third fourth and I want to put uh empty space space between those two so that I can group them group them so I’m going to add here C out and line like this and that should be it pretty much so if I run my program now as you can see it has generated this multiplication table from 1 to 10 okay and it has done that in a matter of less than a second so as you can see here we have this outer counter oh I cannot Mark that only so we have this outer counter which is going to be our I that counts from one to 10 but for each value of our outer counter for so for each value of our I we have to really count from 1 to 10 with our inner counter which is going to be our J as you can see here okay so these are the results of our multiplication operation and I hope that you have seen now how you can really use programming to your advantage how you can use it to solve not really complex but tedious tasks you would really need 20 or 30 minutes in order to write this yourself and you can now generate it with just couple of lines of code and less than a second of your computer’s power to to Really execute this code here that you have written and the most amazing part is that you don’t really have to put 10 here here so we have put 10 here because I want to make this example manageable for this video but you don’t have to hardcode these values here you can really use whatever values you want you can say for example let’s say 2,000 okay so I want to generate multiplications stable up to 2,000 how long would that take in real life so without programming okay now you see a few moments later okay so it is still running and it is going to generate around 4 million records which is a lot and it is going to do that in a matter of minutes so how long would it take for you to even just count from 1 to 4 million it would take you probably days if not months and also there were a lot of errors that you would probably make in that process so I hope that now you can really recognize the power of programming now if you needed to do this task you would really program your computer to do it and now you can just go take a break and your computer is going to finish that task for you so I hope that you can recognize now how you can use programming in order to solve different types of tasks that you can come across in your school in your job or life in general and if you like this video make sure to subscribe to my channel also click the Bell icon and share it with anyone who would like to learn programming and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners in this video I want to show you how you can draw shapes using C++ so before we start make sure to subscribe to my channel and also hit that Bell icon as well so that you are notified when I publish my next video and let me show you now what we are going to do in this video so here where is it here I have image of the task that we are going to do today and that is going to be really to draw this rectangle shape with the desired height and width and the symbol that our user enters okay so that is the task that we are going to do in this video and let’s very quickly analyze this problem and see how we are going to solve it so the first thing that we need is for our user to enter height width and then symbol and after that we will really need to figure out a way so figure out the algorithm on how we are going to draw this rectangle shape here so if you look at this rectangle shape you can really notice that it has the height that is going to be three of these symbols that our user has entered and then it has the width that is going to take four of these symbols that our user has entered for width okay so we are going to use nested for Loop in order to solve this problem here and if you’re not familiar with nested four loop I am going to link that video here because I have already made one video with nested four Loops so make sure to watch that video and in this video I am going to really use that nested for Loop in order to control height and width of our rectangle shape so we are going to have outer for Loop which is going to really control this height and then for each iteration of our outer for Loop we are really going to control this width with another loop and we are going to count from one up to four because four is the width that our user has entered and draw that shape in each iteration of our inner for Loop okay so that is what we are going to do so let’s now translate that into code I’m going to say here first thing that we need is going to be from our user to enter width and height so I’m going to declare two variables the first one is going to be height like this and then with Okay so let’s write out a message to our user so that he knows that he should enter height okay now let’s accept that height value in our height variable and after that let’s really copy this and do the same thing for our width like this and accept that value in our width variable so that is the first step the second step is going to be to declare another variable which is going to hold the symbol that our user wants to use for drawing that shape so I’m going to declare a variable of type Char and I’m going to call it symbol like this and let’s write out a message to the user so that he knows that he should enter that symbol like this and let’s say C in symbol so after we have acquired all the necessary inputs from our user which are height width and symbol that we are going to use to draw our shape now we are left to write the algorithm that is going to draw that rectangle shape so as I already said for that we are going to use nested for Loop so I am going to set up my outer loop the first Loop and I’m going to say four and then I’m going to declare the counter which is going to count the iterations of my outer loop since that outer loop is going to control the height of our rectangle I’m going to say int H so I’m going to give the H name to our outer counter and I’m going to set its initial value to zero like this and then we are going to put the condition how long our outer loop is going to run so while our H is less than height that our user has entered like this and then after each iteration of my outer loop we have to increment the value of our H counter so that would be the setup of our Outer Loop and let’s Now set up our inner loop so I’m going to write four and for this inner loop I’m going to declare another counter which I’m going to call W like this because this inner loop is going to control the width of rectangle shape so I’m going to set its initial value to zero as well and then I’m going to say that it is going to run while this W is less than with that our user has entered like this and also after each iteration we really need to increment the value of this W okay so what we are going to do in this Loop so in this inner loop if you look at this image here where is it okay here you can really notice that in each iteration of our inner loop it just draws this symbol that our user has entered so I am going to very quickly just see out so write that symbol out I’m going to say see out and then write out that symbol like this and there is really one more thing that we need to put and that is going to be after this four Loop so this outer for Loop finishes single iteration we really need to put something else at the end so here at the end of our outer for Loop and let’s look at our image so as you can see here after each iteration of our outer four Loop because it is controlling height and it is really iterating through this inner four Loop in each iteration of our outer four loop at the end of that iteration of outer for Loop we really need to put empty space so here I need to put empty space and that corresponds to this line here so here I’m going to write out C out end line like this and now if I run my program we should really expect to see the shape that rectangle shape of Dimensions that our user defines so let’s say for height four and then for width let’s say for example six and the symbol that we want to use to draw that shape let’s say that that is going to be this plus symbol okay so as you can see our rectangle has the height of four and then it has the width of 2 4 6 so it has the width of six of these symbols that our user has entered okay so there is one more thing that I notice here and that is going to be really to format this shape uh to be a bit more pretty so for that we are going to use the library which is called IO manip so I am going to include that Library here I have to say include IO manip like this and this Library here really contains a function that is that is called set W which means set width which is really going to set the width of the field that comes after it so I’m going to put here that function I’m going to say I’m going to put these redirection signs here and then in this space here I’m going to write out set V so set W actually and then here I want to put what is the width of the field that comes after this function so what is going to be the width of our symbol field and let’s use three for DOT for example so if I run my program again but let me stop it first and if I run it again oh no I haven’t stopped my program so I’m going to close it okay and now if I run my program you can see that it asks height and width again so previously we have entered four and six and then for the symbol let’s enter plus again and now as you can see our shape looks much nicer because of this set width function because it has really assigned to each symbol to each character that our user has entered the width of three Fields okay so let’s run our program one more time and let’s say that that height is going to be five and width is going to be seven and let’s enter another shape so let’s say for example minus and as you can see it has written out the shape so the rectangle shape of these Dimensions that our user has entered and it has used this symbol that our user also has entered so I hope that you enjoyed this video if you did make sure to sub subscribe to my channel and click the Bell icon as well also if you want me to make more videos like this so if you want me to use programming to draw more shapes make sure to write that in the comments down below so that I can know that you really enjoyed this video and like it as well and thanks for watching I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ for beginners and this video is going to be sort of a continuation to my previous video in which I showed you how you can draw rectangle shape using C++ and in this video I want to show you how you can draw triangle and reversed triangle shapes using C++ as well so if you’re not familiar with how you can draw rectangle I would suggest you to watch that video first I’m going to link it here because in my opinion it is a bit more difficult to draw triangle than it is to draw a rectangle shapes so what one more thing I have also created Instagram and Twitter accounts so if you are interested in how developer life looks like and also if you’re interested in behind the scenes of these videos that I post on YouTube make sure to follow me on my other social media so at true code Beauty Instagram and Twitter accounts I’m going to put the link to those in the description of this video so without further Ado let’s start drawing our triangle shape so here I have the shape that we are going to draw in this video and that is going to be this equilateral triangle shape that I have here and there is a couple of things that I want to explain before we start to write code the first thing is going to be that this height our user really has to enter this height so we are going to let our user decide how many of these symbols are going to be on this side and this side and this side as well and the second thing is going to be that our user defines this symbol so which whichever symbol our user wants to use in order to draw this shape we are going to use that symbol that he enters those are two things that we need from our user and then it is up to us to really think and figure out the algorithm that we are going to use in order to draw this triangle shape here so let me explain to you how we are going to do that so we are going to have two four loops and those are going to be nested for Loops so if you’re not familiar with for Loop nesting I’m going to link my video on that here so make sure to watch it so our outer four Loop is the one that is going to control this height of a triangle so in this particular case it is going to have five iterations 1 2 3 4 five and then our inner for Loop is the one that is going to control the width of this triangle and if you really look at this triangle you can notice that our outer for Loop really goes from one up to the number that our user has entered so it has five etration in this particular case because our user has entered five for the length of this triangle so for the length of its sides so that is the behavior of our outer for Loop it goes from one up to five in this particular case and then the behavior of our inner for Loop is going to be the following so in the first iteration of our outer for Loop loop our inner for Loop has only one iteration after that in the second iteration of outer for Loop inner for Loop has two iterations then in the third iteration of outer for Loop inner for Loop has three in a fourth iteration of outer for Loop inner for Loop has four and so on so that means that our inner for Loop goes from one up to the current value of the counter of outer for Loop so let’s translate that into our C++ code let me return this picture here okay so before we start to write that algorithm I am going to create a variable which is going to hold the length that our user enters so I’m going to call that variable length Okay and then let’s write out a message to the user so that he knows that he should enter length like this and let’s store the value in our length variable so that is the first thing that we need from our user and then the second thing is going to be a symbol so that is going to be of type Char like this so I’m going to write out oh see out symbol like this so that our user knows that you should enter symbol as well and let’s store that symbol and our symbol variable so after we have acquired these two things from our user let’s translate the algorithm that I just explained into C++ code so as I said we are going to have two for Loops outer for Loop which is going to have counter that I’m going to call let’s say I and that outer for Loop its counter goes from one up to the value that our user us has entered and it increases by one in each iteration okay so I’m going to say I is equal to 1 and then I is I is less than or equal to length so length that our user has entered and then please increment that I in each iteration so that is going to be outer for Loop and then inner for Loop is going to go from one up to the current value of outer for Loops counter so in the first iteration is going to execute only once so it is going to have only one iteration in the second iteration of outer for Loop it is going to execute twice in the third it is going to execute three times four times five times so how we are going to write that we are going to say four int and then our inner for Loops counter I’m going to call J and J goes from one up to the value of our I so up to the value of outer four Loops counter and it increases by one as well in each iteration and in each iteration it has to write out this symbol that our user has entered so let’s say see out symbol like this okay and then there is one more thing that I want to explain and that is going to be after each iteration of outer for Loop really the next iteration starts in a new line so we are going to write that here here I’m sorry so at the end of our for loop our outer for Loop we are going to say see out end line okay and now if I run this program it asks for length I’m going to say that length is let’s say five and then symbol is going to be star symbol and as you can see it has really written out a triangle that has the length five of these symbols that our user has entered and there is one more thing that I want to do in order to format this shape here to be a bit prettier and that is going to be really to add a function here which is going to assign to each of these symbols that are user enter so that our for Loop writes out uh width of two fields and that is going to be done using a function that is called set W meaning set width and this function here is going to give the space of two fields to the symbol that comes after it and in order to use this function here we have to include its library and that is going to be iio manip Library so I’m going to say include like this IO manip oh okay and now this underline has went away so if I run my program once more and I enter let’s say for length six and then for symbol I enter this this symbol here as you can see our triangle shape looks better now so it has the height or actually the length of six of these symbols that our user has entered and it has also used this symbol here in order to draw this triangle shape and there is one more thing that I want to show you so at the beginning of this video I promis that I’m going to teach you how you can draw triangle shape and then reversed triangle shape as well so there is one very beautiful thing about programming and that is going to be code reusability and about real code reusability you are going to learn when we learn about classes and functions and when I make my videos on functions I’m going to link that video here so make sure to watch it because functions really are one of the most important things that you have to understand not only for C++ programming but for programming in general so make sure to watch that video and let’s say that for now we are only going to really adjust this code here so we are going to modify it a little bit in order to draw this shape here so if you look at these two shapes you can really notice similarities and what are those so this inner for Loop behaves about the same in both of these triangles but there is one key difference and that is going to be that in this triangle shape our outer for Loop Counts from 1 to five and then in this reverse triangle our outer for Loop really counts from five to one so if we modify that we are going to have this reversed triangle so let me move these and then I’m going to really copy this here so I’m going to use contrl C and then control V and then let’s really add a couple of end lines between these two okay like this and then let’s modify this triangle shape that we have just explained and drawn and as you could see on this image here our outer for Loop Counts from five to one which means from the size that our user has entered from one so that means that if we change our outer for Loop we should get that reverse triangle shape so it goes from length like this and it really goes while our I is greater than or equal to 1 and then our I decreases in each iteration so it decrements and now if I run my program it asks me for length let’s say that length is going to be five and then symbol is going to be let’s say this plus symbol and when I pressed enter we have gotten both of these triangle shapes so this one that we have drawn first and then this reverse triangle shape as well I hope that now you have really seeing the real beauty of programming you learn some Basics and then you can use those basics in the most creative ways that you can think of so I hope that you like this video if you did make sure to subscribe to my channel click the Bell icon as well so that you are notified when I publish my next video and a lot more great videos are coming thanks for watching I’m going to see you in my next video bye hi everyone welcome to my channel welcome to the first video of C++ functions if you’re a beginner at C++ make sure to check out my playlist on C++ for beginners and there you can find some of the most important Concepts that you will need to understand and know in order to work with C++ and in this video we are going to talk about C++ functions so functions are one of the most important Concepts that you will need to understand and use in order to be a good programmer and that is not only case in C++ but in most programming languages as well the first thing that I want to explain is what is function function is a block of code that is grouped together and usually that block of code solves a specific problem meaning it performs a specific task and that block of code is executed only when you call that function meaning only when you invoke the function the body of that function is going to be executed and each C++ program contains at least one function and that is going to be main function so this here and the execution of your program starts on the first line of your main function and then it ends when it comes to this last line so this Clos bracket of your main function and also it can end when it comes to return statement but we are going to talk about return statements later in this course so main function is the main one so the first one that is executed and whatever code you put in your main function that code is going to be executed as part of your program so if I say here for example see out and I say hello from main function like this and let’s add a new line like this and now if I run my program you can see that our program has written out hello from Main and that is the first function that our program starts executing besides from main function you can also create your own functions and let’s explain how you can do that so there are a couple of things that you need to know in order to create your own function and that is going to be following so the first thing that you need to really write when you create your own function is going to be return type of your function and that is going to be void for now which means that this function is not going to return anything and we are going to talk about return types more in detail later in this course so for now we are going to use void return type meaning that this function that we declare in this line is not going to to return anything and then you write out the name for your function and let’s call it function like this and then in these parentheses you can put arguments or parameters that your functions that your function really uh receives and for now these parth parentheses are going to be empty meaning that this function does not receive any arguments and then in these curly brackets we are going to put the body of our function so this here is going to be the function that we created ourselves and you have to specify specify the return type of your function after that you write out the name of your function then in these parentheses you can put any arguments that your function receives in this particular case these are empty and we are not going to send any parameters to our function and then here is going to be the body of your function and what we are going to put in this body let’s say see out hello from function like this and let’s also add end line at the end of this function so now we have really created our own function which is called function and if I run my program now what do you think that is going to happen write that in the comments down below so I am going to run this program and as you can see nothing has changed really our program has written out hello from Main as it did before so before we created this function that is because as I explained your function is not going to execute until you call that function so until you invoke it it is not going to execute so in order for our function to be executed we need to invoke that function and how that is done so here in this line after hello from Main we are going to put function and then these parentheses so this here is the invocation of our function and now our function is going to be executed so now if I press this play button you can see that now our console has changed so now we have hello from Main and then also hello from function so that is because we have invoked this function here and you can invoke this function wherever you need it so you can I have invoked it after this line here but you can invoke it as well before this line here if you need to and if you want to so now if I run my program you can see that it first says hello from function and then it says hello from Main because this function has been invoked first and then we have written out this line of code here and that you can see in this console window and let me show you one thing so I’m going to return this after this line of code the invocation of our function I’m going to return here and now I’m going to take this code here so this uh definition of our function and I’m going to paste it after our main function and let’s see what is going to happen now so let me delete these these blank lines and now if I run my program you can see that our program has failed to build so we have compile time errors and in this window here in this error list you can see that it says function identifier not found which means that this function here is really uh our compiler does not understand what this function is because C++ code is executed from top to bottom and when it comes to this line here so when it comes to the invocation of your function it is really not familiar with this function it it does not know what this function is so you have to either put this code before your main function as we did before or you have to do um other thing which is really the recommended way to create your functions and that would be to create definition and Declaration of your function so what are definition and Declaration of function Declaration of function is going to be really this here so I’m going to copy this and put it before our main function and this declaration of function is going to tell to your compiler what is going to be the return type of your function what is the name of your function and then if there are any parameters that your function really receives you are going to put those in these parentheses here so that is going to be Declaration of your function and that part decoration of your function goes before your main function and after that you are going to write the definition of your function and the definition of your function is going to go after your main function and in that way you are going to make your code more readable meaning that when someone else comes to your code and if your code had 200 or three or 400 lines of code then it would be really hard to to read that code and for someone it would be really hard to manage and uh go through your code so he is going to find it much easier if he has all the Declarations of your functions before your main function and then if he needs to read a specific definition of a function he can rightclick the name of that function and click go to definition and then he’s going to be taken to the definition of your function so the specific one that he needs to read so that you don’t bombard um that user with all the functions all the definitions of a fun functions that you have in your program and in this particular situation it is only one function but uh your program is going to consist usually of more than one function and that is really unreadable when you find a lot of definitions of a functions before your main so you can right click on your function and say go to definition or you can press F12 so you can click on your function and then press F12 and you are going to be taken to the definition of your function Okay so so this here is the recommended way to create functions and now if I press play button you can see that our program has executed actually has written out the same as it did before so we have uh really removed that error that we had when we um moved this definition of a function after our main because we have added this declaration of a function before our main function and there is really the most most important thing that I want to mention in this video and that is going to be what is the reason why functions exist okay so we have seen that they make your code a bit more readable so they group the parts of your code together so that you can manage your code easier and the most important characteristic of functions is that they make your code reusable meaning that you can write a specific code once so you can solve a specific problem once put the solution the algorithm the code for that problem in a function and then you can really invoke that function however many times you need it so here I can really copy this and then paste it let’s say three times if I needed it and then if I run my program you can see that this function has been executed three times here and that is really the most important thing about functions which means functions make your code reusable you don’t have to write the same code over and over again and you should really try to group your code in functions so that each function does a specific task nothing more than that and in that way you are going to make your code easier for yourself and for other people as well that are going to read your code so I hope that you understood what functions are and how they are used and we are going to talk about function functions in more detail in my later videos so make sure to subscribe to my channel and click the Bell icon because only then you are going to be notified when I publish my next video and also follow me on my other social media platforms so Instagram and Twitter accounts through code Beauty thanks for watching and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ functions in this video I wanted to talk about function parameters or arguments and the first thing that I want to explain is what are parameters so what are arguments sometimes a function needs to receive a certain value a certain variable and then perform a certain task on that value so on that variable or it really needs the value of that variable in order to perform a certain task so let’s explain how we are going to create a function that receives a parameter in C+ plus so here I’m going to add a function of return type void and I’m going to say that that function is going to be called let’s say um introduce me introduce me like this and then in these parentheses here we can put parameters that our function is going to receive and after that in these curly brackets we are going to put the body of our function so as I said in these parentheses here we are going to put parameters and they are specified in a following way so first you are going to write out the type of your parameter and that is going to be string like this and then we are going to specify the name of our parameter and that is going to be let’s say name so we want to pass in this function that is going to introduce our user we want to really pass the name of our user and then what our function is going to do we are going to put in these curly brackets here and that is going to be really to introduce our user so our function is going to write out C out um let’s say my name is and then let’s write out this name that we have received in this function so I’m going to say name and I’m going to add end line like this okay okay so this is the way to pass a parameter so to pass a value to your function and as I said in my previous video you can really separate this um declaration and definition of a function so you can put really um Declaration of your function here so before your main function and then you can put definition of your function after your main function and if you don’t know how to do that make sure to watch my first video of this playlist okay so now I want to invoke this function here and how we do that well we specify the name of my function so I’m going to say introduce me and then since this this function receives um argument so since this function function receives a parameter here we really have to pass that parameter to our function and that I’m going to put here so here I’m going to pass an argument to my function so I’m going to say Salena like this and this here really is called argument so it is a value that we passed to our function and then here it is called parameter okay so now if I run my program you can see that my function has successfully introduced me so it says my name is Salina like this okay so here we have really here we have really um defined our function so the parameters that our function receives name return type and then uh the block of code that our function is going to execute and then here we have invoked our function and passed an argument which is this string of text here to our function which is going to be received in this name variable and then our function is going to really treat it as a variable which means that it is going to write that value here okay okay and now if I try to invoke this function once more so I’m going to copy this this line and then paste it here and let’s say that I’m going to pass it a different value so I’m going to say for example Anna okay you can see that uh now our function has successfully introduced two users so it has said my name is my name is Salina and then my name is Anna and there is also another thing that I want to explain and that is going to be how you can pass multiple arguments to your function and that is going to be in a following way so here in these parentheses where I have specified my first parameter you can put comma sign and then you specify your second third fourth fifth and um your other parameters so you specify the type which is also going to be string in this particular case and let’s say that my second parameter is going to be called City like this and let’s add another one so let’s say int H like this so now in this function I’m going to write out also where is my user from and also how old my user is so I’m going to write out C out um I am from and then let’s write out this city that we have passed in this function and add also end line and let’s write out also I am I am um age so I am however many years we have passed in this function and then let’s say years old old like this okay so now we have really introduced our user in more detail and we have passed to this function name City and age information for our user but as you can see here our function so our compiler really says that this function is not valid it has too few arguments in a function call meaning that this invocation this call of a function does not really contain all the necessary parameters or all the necessary arguments that we need to pass to our function which means that it really lacks the city and age parameters so here here I’m going to put comma as well and then I’m going to specify my city this here is bolded so it is bold and that means that we have to really pass a city value to our function so I’m going to write out mostar like this and then I am also going to specify age so I’m going to say 25 and let’s do the same for our ni user so I’m going say that our Anna is from New York and let’s say that she has 27 years old for example so now when I run my program you can see that we have successfully introduced two users so my name is Salina I am from mustar I am 25 years old and then also my name is Anna I from New York and I’m 27 years old okay so and we have really written this code only once and then we can reuse it however many times we need to so in this particular case we have reused it two times okay and another thing that I want to explain is going to be a default parameter so what is default parameter sometimes you really don’t want to pass a value to your function meaning that in a specific situation you don’t have that value or you don’t want to pass it and in that case you want to Define define find um theault value for your parameter so in the case where you use where your user does not pass that argument to your function for example you can say that your age parameter here has the default value of zero okay and that means that you don’t really have to pass this age parameter anymore so here I’m going to delete this age for my Anna user and let’s let’s run our program now in order to see how this function is going to behave for this first user and then also to see how it is going to behave for this second user user which did not specify this age parameter so this age argument and when I run it you can see that my first user has been introduced as it was previously so I am 25 years old and then the second user which did not specify age argument it really said I am zero years old meaning that our function has really taken this default value and it has written out I am and then this default value and then years old oh we are missing s here okay so I’m going to add s and I want to do a following thing so in the case where our user does not pass this value for our AG parameter I’m going to really check whether we have that value or we have this default value and then in the case where we have only this default value I don’t want to write this line of code here so I am going to say here if age is not equal to zero meaning that our user has specified some other value which is not zero then and only then we are going to write this line of code but in the case where we have only this default value we do not really want to write out that our user has zero years old cuz that does not make sense okay so as you can see now my first user has been introduced as I am 25 years old and then my name is Anna I from New York since Anna did not specify how old she is we haven’t written out her age here because of this check that we have added okay so that was about default parameter and there is one thing also that I want to um that I want to say about this default parameter and that is going to be really if I delete this is equal to zero and then I try to assign theault value to this city parameter so I say let’s say that city is equal to default like this you can see that the compiler is really underlying this function and it says okay it says theault argument not at end of parameter list meaning that you can specify theault argument only at the end of this list so if you want to specify default value for this parameter you will have to specify default value for this one as well so if I add theault value here so I have added zero then we can really add a default value for this second parameter and then we can add default value for this this one as well and now we are really uh left with so our compiler is not underlying this uh introduce me function name anymore okay and this does not make sense so I’m going to delete it but I wanted to explain that you cannot specify default value for your middle parameter if you did not specify a default value at the end of your parameters list and there is one more thing that I want to show you and that is going to be that you don’t have to hardcore these values as we did here so I’m going to comment these out and then I’m going to let my user Define his own values for these three variables so I am going to declare uh two variables of type string which are going to be name and City and then also I’m going to declare a variable of type int which is going to be called age and then I’m going to say see out so please enter a name like this it’s not capital letter okay and then see in name and then see out City so after my user has entered name I want him to enter City so C in city like this and then also I want to enter age and C in age like this so now after my user has has specified these three variables so name City and age I can pass these three in my introduce me function so I can say introduce me and then pass name and City and age like this and if I run my program now as you can see my program really asks me to enter a name so let’s say that name is going to be Tom for example and then let’s say that city is going to be London and age let’s say 32 okay and now as you can see my function has successfully introduced Tom so it says my name is Tom I am from London and I am 32 years old okay and you don’t really have to use these names for the variables in your main function so the names of these variables here do not have to be the same as these names here here so you can call these for example name one city 1 age 1 but you are going to have to use these names in your main function so you will have to say name one city 1 age one and here as well but these names do not have to be the same as these names here your program is going to work correctly you have to however have the same type here and here so this here has to be string if it has been declared as string here and this one as well and then age also has to be of type int if it has been declared as int here and once more if I run my program you can see that it asks for name so Tom New York and then age is going to be 22 and as you can see my name is Tom I’m from New York I am 22 years old so your program works just fine so I hope that you have understood how parameters behave in a function and how you can pass multiple parameters to your function and also how you can specify a default parameter in your function and if you enjoyed this video If you learned something new make sure to subscribe to my channel click the Bell icon so that you are notified when I publish my next video also like it and share it with your friends and follow me on my other social media so Instagram and Twitter account true code Beauty thanks for watching and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another video of C++ functions in this video I wanted to talk about return statements and return types of a function so what is return type of a function well return type of a function can be any data type that can be used in order to declare variable so it can be int float bull charart double um it can be any user created data type and it can be void as well which means that that function is not going to return anything and as we explained in one of my previous videos function is a block of code it is a code that is grouped together and that code is going to perform a specific task and here I want to make a difference between functions that return value and functions that don’t return value and functions that don’t return value can be for example um an example of a function that does not return value can be a function that writes out a menu to your user so you call that function that function writes out a menu to your user and the job of that function is done there so you are not expecting any value to be returned from that function but an example of a function that returns a value can be a function that performs a specific calculation let’s say on arguments that you pass to that function and after that calculation is performed you are EXP expecting a certain value so result of that calculation to be returned from that function and an important thing is that function can return only one value so only one return statement inside your fun function is going to be executed and I’m going to show that on the example that we are going to do in this video and now I’m going to show you really how functions make your code easier to read easier to understand and how they make your code reusable so we are going to show that on an example which we are going to first make without using a function so we are going to make a program that is going to determine whether a number is prime number or not and we are going to do that first without chosing functions and then I’m going to refactor that program so that it uses functions and then I’m going to show you how that program becomes instantly more readable more understandable and also how that makes your code reusable so as I said we are going to create a program that is going to determine whether our number is prime number or not and the definition of a prime number is a number that is divisible only by itself and by one so if that number is divisible by any other number so not one and not itself but any other number that means that that number is not prime number so the first thing that I’m going to do here is I’m going to declare a variable of type in call it number and then I’m going to let my user enter that number so I’m going to write out the message to my user and then use the C in command in order to get that number and store it in my number variable and then let’s explain the algorithm that we are going to use in order to determine whether that number is prime number or not the definition of a prime number is a number that is divisible only by one and by itself which means that if you can find any other number number besides one and that number itself that you can use to divide it by this number that are user has entered and get the remainder of zero that means that this number is not prime number so how we are going to solve this problem well we are going to iterate through all the numbers between two and this number minus one and then we are going to check whether this number is divisible by that count value so I’m going to write out for INT I is equal to 2 and then I is less than number and in each iteration I want to increase the value of my I counter so why haven’t I used one here and why haven’t I said here that this I is less than or equal to the number because every number can be divided by one so we do not need really to check that and also every number can be divided by itself and we do not need to check that as well so here we are going to iterate through this interval so between two and while I is less than that number that our user has entered and here we are going to check whether this number that our user has entered can be divided by any value of ouri so in any iteration which we are going to go through and in the situation where it can be divided we are going to use a flag which I’m going to declare here and that flag is going to be of type bu and let’s call it is prime flag like this okay and this flag is initially going to be assigned a value of true so we are going to initially say that all the numbers are prime numbers and then we want to prove that wrong for the numbers that are not so we are going to use this flag in a following way here I’m going to check in each iteration if our number that our user has entered can be divided by that current counter so by the current value of I so I’m going to use this modular operation and I’m going to say if this number modulated by I is going to give us the result of zero so when you divide this number by I do you get the remaining of zero and if this operation here results as true we are going to say that our is prime flag is going to be false so we are going to assign the false value to our is prime flag because we have clearly found one number which is not one and that number itself that can be used in order to make this condition true so here I’m going to write out is prime flag and then I’m going to assign it a value of false and and then another thing is going to be really if we find one number so even one number is enough to find that that really fulfills this condition here in order to say that our number is not prime number and in that situation we do not really need to check any more numbers because we have determined that our number is not prime number so here I can use break statement so I can say if you find only one number please do not iterate through this for Loop anymore because we do not need to find any more numbers so in this situation here we have iterated through all the numbers between two and that number that our user has entered we have checked whether that number can be divided by any value of our I counter and if it can be divided meaning that it gives the remainder of zero after that division we are going to set our Prime flag to false and we are going to break from our four Loop and after we have have successfully fulfilled this so after we have successfully iterated through this for Loop or we have fulfilled this condition in one iteration we are going to leave our for Loop and we are going to come to this line of code here and here I want to check what has happened with my is prime flag meaning I want to check whether this is prime flag has has stayed true which means that our for Loop has executed all of its iteration and it has not find any number that can be really used to fulfill this condition here and in that particular situation that flag is going to stay true and that is going to mean that our number is prime number so here I’m going to write out if is prime flag meaning if this value here if this variable here holds the value of true we are going to write out C out like this and we are going to write out prime number like this okay and let’s also add end line here but in a situation where this here does not hold a value of true that means that in uh one iteration so it can be the first one it can be the last one it can be any in between we have really found at least one number that can be used to fulfill this condition and that has set our is prime flag to fals and in that situation we are going to use our else statement and we are going to copy this and we are going to really modify it to say not prime number like this okay so now if I run this program you can see that it asks us to enter a number I’m going to enter a number um let’s say five for example and it says that five is prime number which is correct five is a prime number and let’s run it one more time and let’s say that we want to check six this time and as you can see our program has written out that six is not prime number and six really is not prime number because it is divisible by two and by three besides from one and itself okay so now you have seen how we can really solve this problem and let’s try to refactor this program here in order to use functions so how we are going to do that well the first thing that we need to do is we need to create function and I’m going to do that here and since this part of code here this is the part of code that we are going to move to our function and since this part of part of code here determines really whether our number is prime number or not and then sets this flag to true or false let’s say that we are going to create a function which is going to check as as well whether the number is prime number or not and then it is going to return a value true or false meaning the number is prime number or the number is not prime number and that we are going to write here so here I’m going to put the return type of my function and that is going to be bull so that is the return type of my function and then the name for my function is going to be is prime number like this and then let’s say that we want to pass an argument to that function and that argument is going to be of type int and that argument is going to be really the number that we want to oh the number that we want to check so we are going to pass the number to our function that function is going to in this body here check whether that number is prime number or not and then it is going to return bull value meaning true or false so if the number is prime number it is going to return true and if the number is not prime number it is going to return the value of false and how we are going to do that very simple so you see this code here I’m going to comment this code here and I’m going to really um oh I should have copied it before so I’m going to copy this code here and I’m going to move it to my function okay and we have previously explained this code here so we do not need to explain it again but what I’m going to say here is after this algorithm is done so after we have really uh stored the value of true or false so we have stored the value of false in our is prime flag or we have really kept this True Value inside our S Prime flag what we need to do is we really just need to say return is Prime oh is prime flag like this so after we have checked whether our number is prime or not we can really just return that value from our function okay so we can now after we have moved this code to our function we can delete it from here like this okay and then as you can see we have been left with this is prime flag which is not declared now so identifier is prime flag is undefined meaning that now we have to really declare it and we have to assign it a value so I’m going to say here bow is prime flag like this and then the value that I’m going to assign to my is prime flag variable is going to be whatever value our function returns so here I’m going to say please call my function is prime number oh this prime number like this okay and then pass to that function this argument here so our function expects a value and that is going to be this number that we want to check whether it’s prime or not and then after this function here is done it is going to return a value of either true or false and that value is going to be stored inside our S Prime flag variable okay so now if I run my program you can see that it asks us again to enter a number so so I’m going to say let’s check number nine for example and it says that number nine is not prime number which is not because it is divisible by three and let’s check number um 13 for example and 13 is prime number okay so after we have really used this function in order to perform this particular task I want to show you one more thing and that is going to be how we can refactor this fun function here in order to make it even more simple and if you look at this function here you can say you can see that this is prime flag is set to True here and then in this situation where we find number that can be used to fulfill this condition here we set that is prime flag to false and then we use this break statement in order to break our for Loop so we are not going to iterate anymore through our for Loop when we come to this break statement and then we really go here and then we return that is prime flag but we can do that in a more simple Manner and that is going to be really here so here in a situation where we find number that is really fulfilling this condition here we can say at this very line of code we can say return false like this because this and this code of this code here we can delete and what I can use this return statement because this return statement is going to really break our for Loop and it is going to return the value from our is prime number function meaning it is going to do two things so we do not really need to set the flag and then return the value of that flag at the end but we can really say if you find any number that can fulfill this condition return false immediately so break for Loop and also return the value from our function meaning and the execution of that function because we have found our result and then here as well we do not really need to declare this is prime flag to true and then return it because it is clearly true so we can say here return true and then remove this flag from here like this and then as well I can remove these curly brackets and make my code even more readable so now I want to explain what we have done so here we are passing a number to our s prime number function then we are iterating through all the numbers between two and that number we have skipped one and that number itself because all the numbers are divisible by one and by that by that number itself and then we are checking whether any of these I values between two and number fulfill this condition here that would mean that that number is divisible by that current value of I and that would mean that our number is not prime number so at that very moment we can say please return false because this number is clearly not prime number but in a situation where this for Loop has really iterated through all of its iterations and it has not found any number that fulfills this condition here that means that this return false statement has not been executed and then that in that particular situation this return statement here is going to be executed and this return statement here says return true okay so this part of code here has not changed nor it is going to change and if I run it again you can see it asks me to enter a number I am going to enter number seven then it is going to check whether that number is prime number so it is going to call our function and assign the result of that to our is prime flag variable and I press enter here you can see that we get result prime number because 7 is prime number okay and that is really making your code much more readable and reusable as well so this main function here is much more clean than it was before and now I want to show you the most beautiful thing and that is going to be how we can make this is prime number function reusable so let’s say that I am going to delete all of this code here so I’m going to delete it and now I have I know that I have written out this is prime number function and I know that that I can really invoke this function and use it whenever I need to determine whether some number is prime number or not so let’s say that now we want to check all the prime numbers between 1 and a th000 for example so how we are going to do that well we are going to iterate through all the numbers between one so I is equal to 1 and then I is less than or equal to 1,000 and increase our I in each iteration by one like this and then in each iteration I really am going to just send this I to my function and I’m going to really get the result from this function so this function is going to tell me whether that I is prime number or not so here I’m going to declare a variable of type ball and I’m going to call it is prime and I’m going to assign to that variable a value of is prime number when I pass it the value of I so whatever this function here returns whatever this function here results in I’m going to assign that result to my is prime variable okay and now what I want to write out is all the numbers that I that are prime numbers between one and this thousand value so I’m going to say if is prime like this I’m going to write out C out and then I want to write out the current value of my I counter because that is number that we are talking about so I is prime number number like this okay and I’m going to add a new line at the end so this code here is really going to check all the prime numbers between one and a th and it is going to write out all the prime numbers in that interval and for solving this particular problem so whether the number is prime number or not we have used this is prime number function which we have written once and we have really tested it once we know that it works as it should and now we can really close it we do not need to really think about how we are going to perform this task never again so we have written it we have oh we have tested it and now we have this algorithm stored in our is prime number function and we know that this function Works in a following way so we pass it a value and then this function return returns us true or false variable meaning that the number is prime number or not so once more if I run my program you can see that we have gotten the expected result so we have gotten all the prime numbers between one and a th000 okay and there are a lot of numbers okay so you can check these numbers on your calculator if you want and let’s say now that we really want to check all the numbers between not just one and a th000 but let’s say 1 and 10,000 or 100,000 okay we can call just this is prime number function pass it the value of our I and then check the value that this function has returned and this function has really told us whether the number is prime number or not and if the number is prime number we just want to write that number out to our user so if I run this function again you can see that it is writing out all the prime numbers between 1 and 100,000 and there there is a lot of numbers again so you can even count how many prime numbers there are in this interval so between 1 and 100 ,000 and let’s say that I’m going to leave that part to you so if you want to really uh upgrade this program so that it counts how many prime numbers there are in this interval you can write that code in the comments down below and I’m going to check it and as well you can leave it for other people to see and use if they need it so I hope that you have understood this return type of a function and in this particular situation it was Bull type but you can have as a return type from your function you can have any other data type so you can have float chart int uh string whichever data type you can really uh use in order to create a variable you can use that data type in order to be um return type of your function so in this particular situation I wanted to show you an example of a bit of a more complex function let’s say that is going to determine whether your number is prime number or not and it is going to really receive that number that you want to check as an argument as parameter and then it is going to return only true or false meaning that number is prime number or that number is not prime number and once you have written this code and once you have tested it you do not really need to bother with this function anymore you do not need to remember this code nor read it nor even understand it in order to use this function only in a situation where you have a b bug and that bug is in this particular function only in that situation you are going to need to really reread this function and fix that bug in any other situation you can really just use this is prime number function uh and as well we could have made other functions with other return types we could have created for example a function that is going to um to sum two numbers so you are going to pass to a function two numbers let’s say number a and number B which your user enters and then that function is going to sum those two numbers and it is going to return the result to your main function from where you are going to invoke that function and as well I can leave that to you so you can really practice writing functions on that example for example and you can put the code for that um exercise in the comments down below as well and I’m going to check it and in this particular example as I said I wanted to show you a bit more complex example so that you can really understand why we need functions and why they make our code understandable and reusable and if someone else comes to your code now and he sees that he has um is prime number function he does not really need to open this function and read how this function works it is pretty clear from this this declaration itself that this function receives a number and determines whether that number is prime number or not and returns that true or false back to the invoker back to the function that called that invoked this is primed is prime number okay so I hope that you like this video I hope that you enjoyed watching this video if you did make sure to like it and also subscribe to my channel and follow me on my other social media so Instagram Twitter account at true code Beauty the link is going to be in the description and I’m going to see you in my next video bye hi everyone welcome to my channel welcome to another C++ functions video and in this video I want to talk about concept that is related to functions which is function overloading so I want to First explain what function overloading is it means that you can create multiple functions with the same name but those functions are going to have different parameters so here I have opened my visual studio stud and let’s create a function which is going to be called for example sum and I’m going to put the return type of that function to be int so integer if you’re not familiar with function return types I’m going to link that video here so make sure to watch it so first thing we write the return type of our function and then we write the name of our function and as I said our function is going to be called sum and then I want to pass parameters to this function so I really want to declare which parameters this function is going to receive and those are going to be two parameters the first one is going to be integer and I’m going to call it a and then the second one is also going to be integer and I’m going to call it B like this so this is going to be our first function and let’s also say that we want to create another function which is also going to be called sum but this time it is going to be of return type double like this and then I’m going going to call it sum as I already said and this function is going to receive two parameters as well but those are going to be of type double so I’m going to say double A and then Double B like this okay and as you can see these functions are underlined because it says function definition for sum not found meaning we have declared our functions here but these functions are missing the the definition so definition is missing for this function and and then this function as well and let’s also create one more function so I’m going to say for example float and then I’m also going to call it sum and let’s say that this time I’m going to give it um three parameters so I’m going to say float um let’s say float a and then float B and then float C like this okay and then what I want to do is I want to create definitions for these functions which I’m going to do here here so the first one that I want to Define is going to be this one here so I’m going to copy its declaration and then I’m going to add these curly brackets and here I’m going to put a definition for this function so let’s say that I’m going to create a variable of type int and I’m going to call that variable result like this and I’m going to assign it the result of a + b like this and then what I want to do is return this result from my function fun so here I’m going to say return result like this so this would be one way of returning the result from your function and then another way to do the same thing is going to be to say really return here so instead of creating a variable that is going to hold this result you can really return this result itself from your function so you can say here return A+ B and now we can delete this line and as you can see this function became shorter and more readable so now I want to Define this function here so I’m going to say double okay I should have copied this and then double b as well like this so here I want to put the definition for this function here and this function oh I’m missing the name for my function it is called sum so this is return type this is the name of our function and then these are parameters of our function and here I want to say return a + b as well but this time our a and our B are going to be of type double so in this situation there were integers and then in this situation there are decimal numbers okay and let’s also create a definition for this function here so this float function and this time I’m going to copy it okay and I’m going to add these curly brackets and here I want to write return and then A + B + C like this okay so now how we are going to test this we can call these functions we can invoke these functions here in our main function and the first one that I want to invoke is going to be our in function so I’m going to say C out and then this line of code is going to write out whatever our function returns so I’m going to say please write out whatever my sum function returns and then I want to pass to my sum function two numbers and those two numbers are going to be two integers and as you can see here we have really helped from our Intel ense which says you have three possible functions that you can call so you have overloaded three functions and you can navigate through these using your arrows so the first one is going to be our function that has float return type and that function return that function receives three parameters of type float and then the second one is going to be the one that has return type double and that function receives two double parameters and then the third one is going to be the one that returns integer and that function receives two integer values so here I want to call our integer function and I want to pass to that function four and three for example and let’s also add end line like this and now if I run my program we can expect to see the result of this line of code here and as you can see the result is seven meaning that our function has been invoked and then this line of code has received the result of summing these two numbers and that has been written out in our console and the result of summing four and three is seven Okay so now I’m going to stop this console and I want to test these other two functions so I’m going to say see out and let’s test our some function that receives two double parameters so it is going to be this one here so I’m going to say 4.4 and then 3.3 for example and I’m going to add end line at the end as well okay and now if I run this program you can see that our second line is is 7.7 meaning 4.4 + 3.3 is going to be 7.7 which is correct so we have successfully tested this function here so this double function that returns double and receives also two double parameters and then let’s also test this third function so here I want to say C out sum and then here I want to pass three parameters the first one is going to be let’s say four .4 and then the second one is going to be 3.3 and then oh three decimal points 3.3 and then the third one is going to be 2.2 for example okay now this invocation should invoke this float function so when I run my program as you can see here this third line contains the result of summing these three numbers and you can check this out using a calculator but this is the correct result so as I already explained this represents function overloading and we have created three functions the first one is the one that receives in types and returns in type as well then the second one receives double so two double uh variables two double parameters and returns double as well and then the third one really contains three arguments so three parameter parameters but it has the same name as these previous two and then it returns float type as well and then now when we call when we invoke those functions we can really pass different data types and depending on those data types we are going to call adequate function so in this first line we are going to invoke this and then in this second line we are going to invoke this and then in our third line we are going to invoke this okay so I hope that you understood what function overloading is and also I hope that you have understood that you don’t have to create functions with different names when they are doing uh almost the same thing so these three functions these three are doing the same thing they are summing the numbers that we pass to them only in this particular situation the first one is summing integers the second one is summing decimal point numbers and then this third one really sums three numbers and we have overloaded this sum function and we didn’t have to create functions that are for example sum int and then some double oh double and then some float like this so we didn’t have to name these like some int some double and some float but we can use the same name as long as we have different parameters different number of parameters different return type or something similar in that particular situation our compiler is going to decide on its own which function it should call I hope that you have understood what function overloading is and how you can use that thanks for watching and I’m going to see you in my next video bye hi everyone welcome to my channel my name is Salina and I make it and programming related videos so if that is something that is of interest to you consider subscribing to my channel and give this video a thumbs up as well now in this video I want to show you how you can build an ATM application and the first thing that I want to do in order to build this application is going to be to plan the functionalities that this application is going to have so I’m going to put a comment here and then here we are going to write all the functionalities that our ATM is going to have so the first one is going to be to check the balance so I’m going to write that so check balance and then another functionality is going to be to deposit money so let’s say deposit like this okay and then what else well we should be able to withdraw money as well so let’s write that okay and I definitely want to show the menu to my user so I’m going to write that as well so I’m going to say say show menu like this okay now after we have written these functionalities that we want to implement the first one that I want to implement is going to be this show menu function so I’m going to put the code for this show menu functionality in a function and let’s create that function here so I’m going to say void it is going to be of void return type let’s call it show menu like this oh like this okay and then what I want to do here is I want to write out the menu to my user so I’m going to say see out and then let’s add these star symbols four 5 6 7 8 9 10 that is going to be enough like this and then I’m going to copy this on the other side so that it looks proportional okay and then the first option that I want to write out my user is going to be uh let’s add first and then check balance so that is going to be the first option that our user can choose and then let’s add couple more of these so the second option is going to be deposit so I’m going to write that like this and then the third option is going to be to with draw so I’m going to copy this here and then paste it here okay and then let’s add these star symbols at the end of our menu like this okay now after we have created this show menu function what I want to do is I want to invoke this function so here I’m going to say um show menu like this okay and if I run my program as you can see we have this menu shown to our user now what should happen next is we should allow our user to choose one of these three options so the next thing that I will do is I will create a variable so let’s create it here let’s say int and that variable is going to store the option that our user chooses so I’m going to call it option like this and then here after I have written out this menu so this menu here to my user I’m going to say see out and then please choose an option or whatever message you want to show so option like this and then I want to accept the value that my user enters in this option variable so I’m going to say C in option like this okay now if I run this program again as you can see it asks for option and if I select any of these three options if I press three for example you can see that my program closes because we haven’t written any code after this line here so what I want to do now is I want to handle these three options and I’m going to handle these three options using a switch case so I’m going to write switch okay and then here I want to put this option variable so that is going to be the value that I want to check so I’m going to say switch option and then in the case that our user has entered option one what I want to do is I want to write out the balance to my user and in order to do that I’m going to create a balance variable because we do not have a balanced variable yet so I’m going to give it a type double like this and call it balance okay and let’s assign it initial value of uh for example 5 100 okay so that is going to be the initial value of our balance um variable so here I’m going to say C out and then let’s say balance is okay and then let’s write out this balance variable and I’m going to add this dollar symbol at the end and I’m going to add end line as well okay so that is going to happen in the case that our user enters value or option one and I’m going to add break at the end of each case so here as well okay now our second case case is going to be when our user enters option two like this so in that second case we should allow our user to deposit money so here I’m going to say see out and then let’s write out um deposit amount so we want to ask our user how how much money he wants to deposit so in order to accept the value that our user enters I’m going to create a variable which I’m going to call deposit amount so let’s create that variable it’s going to be of type double and it is going to be called deposit amount like this and then I’m going to accept the value that our user enters here in my deposit amount variable like this okay and now what I want to do with this deposit amount is I want to add it to my balance so I’m going to say balance is now going to be equal to whatever my balance was previously holding plus this deposit amount like this and then let’s add break at the end as well okay and then our third option our third case is going to be when our user wants to withdraw money so I’m going to copy this case here and then paste it here and here I want to write out a different message to my user so I’m going to say withdraw amount let’s copy this okay and then this variable I’m going to call it withdraw amount like this okay and then here I want to enter that withdraw amount and what I’m going to do with my balance in that situation is going to be I want to subtract that withdraw amount from my balance but I want to subtract that withdraw amount only in a situation where this withdraw amount is equal to or less than this balance so I’m going to say here if withdraw where it is withraw amount is less than or equal to balance like this then I want to give that money to my user else meaning if our user has has requested more money than he has I’m going to write out a message so I’m going to say not enough money like this okay and that is going to happen so this code here is going to happen in the case that our user enters option three which is this one here okay so now if I run my program you can see that it asks option and let’s see that we want this first option so this check balance and it says that balance is 500 and if I press anything else as you can see my program is going to close and that is because we haven’t implemented any Loop that is going to iterate this code here so let’s add that Loop now so here I’m going to say do so do while loop is the one that I want to use and then in inside my do while loop I’m going to put all of this code here so let’s add a curly bracket close curly bracket at the end like this and then I’m going to say please do this block of code here while and then I want to do this code here while the option that my user has ento option that my user has entered is not equal to four four and when my user enters option four we should stop the execution of our program so in order for our user to know that for means exit we are going to write that here in our show menu function so here I’m going to add this fourth option which is going to exit our program like this okay now if I run this code you can see that it says that it has this menu here and then it asks for option so I’m going to enter option one for example okay and this option one says that balance is $500 now let’s enter this second option let’s enter this deposit option so I’m going to press two and as you can see it says please enter deposit amount so let’s say that I want to deposit $700 for example okay now if I check my b balance again so I have entered this option one and then I press enter as you can see it says that my balance is $1,200 and there is one thing that I want to do with this program because I don’t like the way that this looks it is not really readable so I’m going to add um clear screen so clear console command and I’m going to add that here so after my user chooses his option I want to clear the console so I’m going to say system and then let’s add CLS which is a command that is going to clear my console clear my um window so if I run my program again as you can see again we have this menu and then it asks us for the option so let’s say that I want to check my balance it says that my balance is $500 now let’s try to withdraw money let’s say that I want to withdraw money and I want to withdraw $600 for example and then it says not enough money because we had $500 um on our account so now what I want to do is let’s say for example that I want to deposit $100 okay and then I want to withdraw $600 okay and if I check my balance now as you can see balance is zero and in order to test this exit functionality let’s press for and then if I press enter as you can see my application is going to close now another thing that I want to check is going to be what is going to happen if our user enters option that is not valid meaning an option that is not any of these for that we have covered here so if I run my program again as you can see um it asks us to enter options so I’m going to enter option five for example which is not valid and nothing has happened happened if I enter option n nothing has happened again 99 okay now you get the point what is happening here is our program tries to find this adequate option so option five option n whichever one we have selected and since that option does not exist in these cases here our program continues to this while check and then it checks that the option is not equal to four and because our option is five or 9 or 99 which is not equal to 4 then our DU while iterates again and then it writes this show menu again and then it asks us to enter this option again so these three options are the only valid options that you can select and then four means that you are going to exit your program now here we have created this show menu function that has uh check balance deposit withdraw and then this exit option and what I want to suggest to you is how you can upgrade this program on your own so for example you can create two users two accounts and what you can do with those two users is you can Implement transfer option meaning um transfer money from one account to the other account and I’m going to leave that up to you and if some of you decide to write that code make sure to paste it in the comments down below and I’m going to review that code and and some other people may find it useful as well so I hope that you enjoyed this video if you did give it a thumbs up don’t forget to subscribe to my channel and hit that Bell icon as well and I’m going to see you in my next video bye hi everyone welcome to my channel my name is Salina and I make it and programming related videos so if you’re interested in those please subscribe to my channel and give this video a thumbs up because that helps me a lot to reach more people and spread programming knowledge and in this video I want to talk about generics and templates in C++ so what are generics the idea of generics was born when programmers decided that they want to be able to use the same code but with different data types so the logic is the same but data types are different or if you want another explanation when we talked about functions we said that we can pass parameters to functions and what we said as well is that types of those parameters had to be known beforehand so you had to hardcode types of those parameters whether it is int or Char or float or any other data type that had to be known beforehand but with this idea of generics what we should be able to do is we should be able to pass that type itself to a function so we should be able to determine which type we want that function to operate on and the best way for you to understand and this will be on an example so that is exactly what I will do so let’s say that in my visual studio I want to create a function that will swap the values of two variables and if you don’t have an idea how you can swap values of two variables I have a video where I explained that uh in a very visual way so you can use that video I will link it here so here I will just type very quickly the code for that and if you need explanation again you can watch that video so I will say that that function will be of return type void and I will call it Swap and then what I want to pass this function will be two integer variables so I will say int a and then int int B like this okay but because I want to have both of these variables available in my main function which will invoke my swap function I will have to pass these two variables using a reference and again if you’re not familiar with passing parameters by a reference I will link another video here where I talk about that and I think that I made more than one video on my channel talking about passing variables by a reference to a function so I will put those in the description as well so the code for this swap function will be the following so I will say int temp I will create a temporary variable and to that temporary variable I will assign the value that my variable a is hold holding and then I will assign to my variable a the value that my B is holding like this and then to my B I will assign whatever my temp variable is holding again if you need to understand this in more detail I will put video in the description of this logic here okay so now this function should give us the ability to swap values of two variables and the way to test this function is the following so I will say please create two variables call them A and B like this and to my a variable I will assign the value of five for example and then B will have the value of s so let’s write out values of these two variables let’s say a and then just make a separation and then value of B like this okay so now what I want to do is I want to invoke this swap function I will say Swap and then I will pass my a and then B like this and if I copy this line after the invocation of my swap function we will see if the values had indeed been changed so if I run my program as you can see this line of code here has resulted with this output so 57 and then after invoking our swap function the values inside these two variables so A and B have successfully been swapped so now it is 75 okay excellent so that means that this function does what it should do now what happens if I want to swap values of two Char variables for example what I would have to do is I would have to copy this function paste it here and then I will adjust it to be able to work with Char variables so I will say Char and then I will change this with Char as well and then here I will put Char as well now this swap function should work with char parameters and this is called function overloading if you’re not familiar with function overloading I made that video explaining how it works so I will link it here if you want to watch it and I will put it in the description as well so this function should be able to work with Char parameters now and in order to test this function let’s create two variables of type Char so Char C and then d as well and to my C variable I will assign the value of letter C and then to d i will assign the value of letter D excellent so I will copy this line of code here and I will just adjust it so that now we write out the value of our C variable and then here we write out the value of my D variable like this and then after this line of code here I want to invoke this swap function so I will say Swap and then pass it C and D like this and I want to write out my C and D variables after this line of code here so after I have swapped the values just to check that they successfully have been swapped so if I run my code as you can see we have this out output here so c and d and then after swapping the values inside these two variables we have this output here which means that they have been swapped successfully now um I see a problem with this approach here and the problem is following what happens if I want for example to swap values of two float variables and then two doubles and then two booleans and so on well I would have to create this swap function for each data type and that is repeating code and we shouldn’t really be repeating code unless we really need to and in this particular situation we don’t so there is a simple solution for this problem and that simple solution will be using generics and the idea is to be able to use the same function the same logic but with different data types so again we will be solving this problem using generics and the way that generics are implemented is using templates so how do you make a template in C++ well you use keyword that is template like this and then inside these angled brackets you will put the name of your type so you will say type name and um most common type name that is used is called T but you can use whichever type name you want you can say type as well if you want that should work but I will use T because that is the recommended way so now that I have created a template and I have said I want to create a new type which is called T I will have to use this T in my swap function so now I will change this int with my T so I will say t here and and then T here and I will create T here as well okay now this T is called generic data type and this swap function is now a generic function which means that this swap function can be used on any data type whose variables can be swapped using this logic here so in one invocation it can be swapping integer variables and then in another it can be swapping characters and then in the next one floats and then doubles and booleans and so on on so now that means that we can really remove this swap function because we do not need it because as we said this function here is a generic function and it can be used with different data types so now I will delete this swap function here and if I run this code this code should work as it did before so let’s press this button okay and as you can see 57 and then 75 this function indeed works for integers and then CD and then DC so it works for characters as well and let’s close this okay now what you can do here as well here in the invocation in this 15th line invoking this function for two integer variables what you can do is you can specify the type itself as well so you can say I am invoking this swap function for my integer type so now when this function is invoked it will go here and this T keyword will be changed with this int so it will be int here and then int here and then int here and it will do the swapping this function here will do the swapping for INT data type and then in this 20th line here you can say as well Char if you want you don’t have to that process will happen automatically because you have declared C and D as charart type so those C and D of type chart will be passed here and then Char will be here here and Char will be here and then Char will be here as well so what we have acquired with this template function here is to be able to use the same code with different data types we have just demonstrated how that can be invoked for integer data type and then how we can use it for character and you can do on your own float or double or bull and so on okay and then what you can do as well is you can use any other name for your generic type T is something that is used commonly in literature but you can use type as well if you want so you can say oh you can say type and then you would have to say type here and then type here and here as well okay that should work the same way that it did previously and then another thing that you will find in literature is instead of this type name keyword you can use class um it really depends on you whichever one you want to use you can and again if you know what classes are class is a type as well so it is userdefined type so this should work as well the same way that type name keyword did and if you’re not familiar with classes and objects and objectoriented programming I have course which I will link here so make sure to watch that so I hope that this video helped you understand what are generics and templates and what is the main idea behind them and we will be talking about this of course in my future videos and in more depth so so make sure to subscribe to my channel and hit that Bell icon as well so that you don’t miss a video that I publish and if you like this one please give it a thumbs up that helps me to reach more people and help more people with programming so thank you very much for watching and I am going to see you in my next video bye hi everyone welcome to my channel my name is Salina and I make it and programming related videos so if that is something that is of interest to you consider subscribing to my channel and in this video I want talk about recursion and recursive functions in my previous videos we already talked about functions in general so you should be familiar with that and then in this video I want to show you on an example what is recursion and how it works so what is recursion recursion is a process where a function invokes itself and that function that invokes itself is called recursive function that is pretty simple definition so let’s show that on an example and the example that I want to give you today in this video will be the sum all the numbers between M and N which are the numbers that our user defines and the first thing that I want to show is we will solve that problem using Loops which is a solution that you should already be familiar with and if you don’t understand Loops you can find videos on Loops in my C++ for beginers playlist so you can watch that and then after we solve that problem using Loops I want to show you how you can solve that same problem using recursion so if you want to skip directly to the recursion part I’m going to leave the link to that part the time stamp in the description of this video so that you can navigate yourself directly to the recursion part if you want now as I already said the problem that we want to solve in this video is going to be to sum all numbers between number M and N so let’s write the text of our task here I’m going to say sum number first between M and N okay so this is going to be our task and then here as I already said I will first solve this problem using Loops so considering that we have to sum numbers between number M and N I will create two variables so int M and N which are two variables to hold the numbers that our user enters you can do that part I’m going to hard code those values here so let’s say that my number M that my variable M holds value of two and then n holds the value of four for example uh and one thing if you are going to ask your user to enter the numbers for these two variables what you should do is you should make sure that your user enters smaller number in your variable M and then greater number in your variable n and if that is not the case there are a few ways to solve that problem so you can swap the values in those in these two variables if your user enters bigger number here and then smaller one here and if you don’t know how to swap the values into variables I’m going to put a link which contains the explanation for that here and then you can as well just ask your user to enter again and again and again until this number is smaller and then this one is greater uh and as I already said I’m just going to hard code these two values here okay so now that we have our number M and our number n what I’m going to do is I will write a loop which is going to solve this problem here and the easiest way to solve this problem here is going to be using four Loops so I will say four and then I will declare a counter in I and that counter should start at the value of our variable M so I is equal to M and then it should count until it comes to the value of n so while our I is less than or equal to n oh sorry so while our I is less than or equal to n and then in each iteration I’m going to increase the value of my counter by one okay so what I should do in this for Loop here is I will just sum all the values that my counter holds in a specific iteration so I will create a variable here which is going to be of type int and I will call it sum and initial Val for our sum will be zero because zero is neutral when it comes to adding so here I will write sum is equal to whatever our sum was previously holding and then to that I will add the value of my I counter like this so this should be pretty much it to solve this problem and at the end of this for Loop we should have the sum of the numbers between two and four in this variable here so let’s write that out I will say C out out sum is equal to and then write out the value that are sum variable holds and if you are not familiar with this code here you should watch my video related to for Loop and I’m going to link it here or leave it in the description down below so let’s run our program and test this code here okay it says that our sum is equal to 9 so 2 + 3 is 5 + 4 is 9 so that is the correct result so this approach here will solve this problem using loops and this is something that you should already be familiar with and now I’m going to show you how you can solve the same problem using recursive functions so let’s comment this code out because I don’t need it anymore like this and then what I want to do is I want to create a function of return type int and I will call it let’s call it recursive sum like this okay so this recursive sum function will receive two parameters and those two will be integer number M and then integer which is called number n so we will pass these two values to our recursive sum function and what should we do inside this recursive sum function well the same way that we do not want this four Loop to be an infinite Loop we do not want our function to be an infinite recursion so here we specified the condition when our for Loop is going to stop to execute so here when our counter I reaches the value of n that is the point when our for Loop stops running and then here in our recursive sum function we will have to define a base case which is going to break this recursion so as I already said it is called base case and for this recursive sum function our base case will be following so I will say if our m is equal to n in that case what I want to do is I want to return from this recursive sum function value of our M or n so I will say return M it doesn’t really matter which one you return because here we have checked that they are equal okay so this here is our base case something that is going to break our recursion so that we do not end up with an infinite recursion okay and then what I want to do here is I want to do that recursive part so that part where the function is invoking itself and what we should do here is the following so I will say return and here I want to return the value of M so the current value of our M parameter and then I will add to that the following expression so I will invoke again our recursive sum function but this time I will pass to this recursive sum function the value of our m + 1 and then the value of our n variable okay so what this code here is going to do the same way that here we have increased the value of our I counter in each iteration here I’m increasing the value of our M parameter in each recursion so that at a certain point we are going to reach this condition here so our M and RN will be equal and at that point our recursion is going to stop so how is this code here going to behave well let’s write out invocation of this function here and then we are going to go line by line through the execution of this program so that you can understand how this recursion is going to work so let’s say see out sum is equal to and then I will invoke this recursive sum so recursive sum and here I want to pass the value of M and N like this so when we come to this 14th line of code here what is going to happen is we will pass values of two and four to this function here so I will write that my M holds the value of two and then n holds the value of four okay and then we come to this line of code here and we check is our m equal to our n so is 2 equal to 4 the answer to that is no so we do not execute this but we go here and what this line of code here says it says please return from this function the following so return current value of my M which is two and then to that I will add whatever this recursive sum function returns to me if I pass it m + one and N so here I will invoke function again and I’m going to use these parentheses to indicate invocation of a function so here we are invoking recursive sum function again and this time we are passing it values of n + one which is three and then n stays the same because our n is our upper limit so that we can know when we are going to break this recursion so here is the invocation of this function again and then we have entered this function using these two parameters so we go here again and we check again is our m equal to r n so is 3 equal to 4 the answer to that is no so we do not execute this line of code but we go here again and what this line of code here says it says please return current value of M which is in this recursion three and then add to that whatever this recursive sum function returns for these parameters here so here I will invoke recursion again and I will indicate that again with these parentheses so we inv invoke our recursive function again with parameters of n + 1 which is four and then n stays the same so we go here again and we check is 4 equal to 4 and the answer to that question now is yes so now we return the value of RM which is four so here I will say that this recursion Returns the value of four and then we go backwards so here we have all the invocations of this recursive of some function so the result the end result of this recursion is going to be the result of this expression here so let’s calculate what this recursive sum function is going to return finally at the end so this is one recursion and that recursion Returns the value of four so I’m going to delete these parentheses and then the recursion prior to that returned the value of 3 + 4 which is 7 and then if we come out this recursion as well so I will delete these parentheses the result of our recursive sum function will be the result of this expression so 2 + 7 will be equal to 9 so this is going to be the result of our recursive sum function so if I run my program now we should get this nine as the result of executing this recursive Su function so let’s run our program and as you can see some is equal to 9 and if I increase these M and N values so if I say for example please calculate some between 1 and 4 we should get 10 this time so 10 okay and then here if I add number five for example we should get value of 15 right so we get that the result is 15 and what you can do here now of course you can say please calculate some of the numbers between 1 and 551 for example but this is going to be hard to check so if I run my program as you can see we get uh this very very big number okay one very important thing that you must have each time that you work with recursion is the following so every time that you work with recursion you must have this base case here which will stop the recursion from happening again and again and again so this base case here will stop invoking recursive some function at a certain point when a certain condition is reached and unless you have that base case which will stop the recursion you will have that function invoking itself infinitely so infinite number of times and you will get an error so in order to demonstrate that I will remove this base case here so let’s comment it out and if I run my program now as you can see we get un stack Overflow error which means that as I already said this recursive sum function is invoking itself again and again and again infinite number of times and this recursion never stops and in order to stop it you need to have a base case which will stop the recursion so I’m going to close the program now and I will return this code here which is our base case and if I run my program again as you can see we get the expected result and the error has disappeared so that is something very important to remember each time that you use recursion you must have a base case to break that recursion from happening infinite number of times so I hope that you understood what is recursion and how it works and in order to practice on your own I will leave a task for you and the task is following so I want you to do the factorial of a number using recursion calculate factorial of a number using recursion and if you are not familiar with what factorial is or how it is calculated I will leave a video link here where I’m calculating factorial of a number using loops and then what I want you to do is to do that same task using recursive functions and you can paste your code in the comments down below so I hope that this video helped you understand what is recursion and how it works and if it did give it a thumbs up and subscribe to my channel and also you can follow me on my other social media if you want the links are in the description thank you very much for watching I’m going to see you in my next video bye hi everyone welcome to my channel my name is Salina and I make it and programming related videos so if that is something that is of interest to you consider subscribing to my channel and give this video a thumbs up as well now in this particular video I want to talk about objectoriented programming so what is objectoriented programming well oop or object-oriented programming allows you to represent real life objects in programming and those real life objects are going to be represented together with their attributes and then their behaviors as well one of the most important concepts of oop are classes and objects so let me explain difference what is a class and then what is an object a class is going to represent a template meaning a blueprint and then an object really represents an example of that class an instance of that class for example a class can be a fruit and then an object of that fruit class can be an apple a banana a peach or another example a class can be a car and then an object of that class can be a Volvo a Ford a BMW and so on and that car class for example has some attributes and then it has some behaviors as well now what are attributes of car class well a car has a name for example that’s an example of a one attribute and then it has a price and Max Speed and color and so on and then behaviors of a car can be drive for example and then break a as well and then change color and so on so here we are going to create an example of a class and then we are going to create an object of that class so the class that I want to create is going to be called YouTube channel so in order to create a class you write class and then you give a name to your class so here I’m going to say YouTube channel like this and then you put these curly brackets and at the end you will have to put a semic column and now here you will put the members of this class now one thing that I haven’t mentioned is that class is user defined data type we have already talked about data types in this course or in C++ for beginners course so if you haven’t watched that make sure to do so I’m going to link it in the description and then here as well so we have talked about basic data types such as integer floating Point number and then Boolean character double string you know but a class is going to be a user defined data type which is going to allow you to represent a real life object in programming and in this particular situation I want to represent a YouTube channel so let’s think of attributes of a YouTube channel what is something that describes a YouTube channel let’s say for example that each YouTube channel has a name so so that is going to be a string variable let’s say string name like this so these attributes are going to be represented with variables so one of the attributes is going to be name and then let’s say another is going to be string owner owner name like this and then let’s think of another attribute let’s say that each YouTube channel has a subscribers count so in subscribers count like this and then let’s as well create a list of published videos so I’m going to say list and let’s call it published video titles so that is going to be type string and it is going to be called published like this now here it says that that this list cannot be used because we haven’t included um it here so here I’m going to say include list and now this should be accessible okay now we don’t have that error anymore and what I want to do here is I want to represent a YouTube channel that has four attributes it has a name then owner name you can use email here or whatever and then it has subscribers count and published video titles now here you can use another class here you can say for example list of videos you can create another class that is called video and then in that video class you can put all the attributes that describe a video so that can be for example a title and then a description number of likes number of comments number of views um the duration of that video the video itself you know but for the Simplicity of this particular exam example I’m going to use just the title of those videos so now after I have created this YouTube channel class what I can do is I can create an object of that class so let’s say here that I’m going to create an object so how you do that you say the type so you put the name of your class which is YouTube channel and then you give a name to that variable let’s call it YouTube channel like this okay now what I want to do is I want to assign values to these properties of my YouTube channel and how do I do that well you say YouTube channel and then you put dot and here is nothing available but it should be these properties should be available when you say YouTube channel dot now why these are not available it is because all the members of your class are by default private and that means that these members because they are private they are going to be accessible only within this class here and in order to make them public in order to make them accessible outside of this class you put Public Access modifier so you say here public okay like this now this public is an access modifier and it is going to make all of these members of your class accessible outside of your class which means that now if I press dot here as you you can see name owner name published video titles and then subscribers count is available for me now so I’m going to say that the name of my YouTube channel is going to be for example code Beauty like this and then owner name let’s copy this a couple more times so owner name is going to be my name so Salina like this and then subscribers count well let’s say this is an integer variable so we don’t need the quotation marks let’s say 1,800 uh people and then these published video titles so let’s add value to my published video titles list so here I want to say that I have published for example um C++ for beginners oh let’s say video one okay and then let’s say HTML and CSS video one okay and let’s add as well this video so let’s say C++ o o video one okay now after I have assigned value to these properties what I can do is I can write out these properties so I can say here for example see out and then let’s say name and let’s write out the name of my YouTube channel like this and I’m going to add an end line and I’m going to copy this couple more times like this so here I want to write out owner name so let’s put YouTube channel. owner name and then here I want to write out a subscribers count so YouTube channel do subscribers count and then published video titles now this property here published video titles is not a simple property meaning this property here is a list and in order to write out a list we are going to use a loop so I’m going to delete this and then here I want to create a loop and let’s say that we will be using for each Loop so I’m going to say four like this and then here I’m going to write out the type of the value that I’m going to use in my list so I’m going to say string because this published video title is of type string and then here I want to give it a name so I’m going to say video title like this and then I’m going to specify the list that I want to iterate and that list is going to be this one here so it is going to be a list of published videos in my YouTube channel object okay and now in these curly brackets I am going to specify the block of code that is going to be executed in each iteration so what I want to do with this video title is I want to write it out so I’m going to say see out and then let’s write out video title and I’m going to add an end line at the end as well and one more thing that I want to write out before this list is going to be just see out videos like this okay and let’s add end line at the end so that it is formatted nicely so now if I run this program as you can see it has written out information about this object that we have created here it says that the name of YouTube channel is code Beauty and then owner name is salinaa subscribers count is equal to 1800 and then the this channel has published three videos so C++ for beginners and then HTML and CSS video one and then C++ objectoriented programming video one okay so uh I have created a class that is called YouTube channel I have uh created four attributes so four properties and made them public which means that these four properties are going to be accessible outside of this class and we have accessed those properties here so we have said uh that we want to assign value to our name property and then owner name sub subscribers count and then we have as well um assigned value to this published video titles list okay and then here we have written out information that is stored inside these properties so that was an example of how you can create a class and then how you can create an object of that class as well and in my next video we are going to be talking about Constructors and class methods because there is a more simple way to do this that we have done here so make sure to check that video out as well so I hope that you enjoyed this video if you did give it a thumbs up and also please subscribe to my channel and click that Bell icon and I’m going to see you in my next video bye hi everyone welcome to my channel my name is Salina and I make it and programming related videos on this channel so if that is something that is of interest to you consider subscribing and give this video a thumbs up as well and in this particular video I want to talk about Constructors and class methods so here I have some code that we have written in a previous tutorial of this course so if you haven’t watched that make sure to check it out I’m going to link it here and in the description as well and let’s explain very quickly this code that we have here so I have created a class called YouTube channel and that class has four public properties so four attribut attributes those are name owner name subscribers count and then a list of published video titles and then here I have created an object of that class I have assigned the value to the to these properties here okay and then here I have written out information about this object that we created and as I said said in this video I want to talk about Constructors and class methods and how am I going to explain these well let me first introduce a problem to this approach here so that you can really understand the need for these two so what happens if I want to create another object of this YouTube channel class how am I going to do that well in this current situation what I would do is I would copy this so I’m going to copy it and then I’m going to paste it here like this and let’s give it a name let’s say that this channel is going to be YouTube channel to and let’s call it let’s say YouTube channel 2. name let’s say that it is going to be called Amy SS for example and um owner is going to be a girl called Amy and then she is going to have let’s say 2,000 subscribers okay and and then the videos that she has published are going to be songs obviously because she has a channel named Amy sings so let’s say that she has published for example um let’s say Johnny B cover like this so that’s one song that’s one video and then let’s say that another video that she has published is going to be for example um Laura Li so that’s a song from scorpions and she has made a cover of that song like this now these two are two of my favorite songs and you can put whatever you want here in this list and I’m also wondering and you can write that in a comments down below what are your favorite songs so please write that in the comments just don’t put links because I think that YouTube has this policy of treating um links as U advertising or spam or something so just write out the name name of your song and then uh the name of a singer I guess and I’m really looking forward to reading your comments so now that I have created this second YouTube channel what I want to do is I want to write out information about this channel but I noticed that I’m missing here uh this YouTube channel to so here I’m going to say YouTube channel 2. ownername and then YouTube channel 2. subscribers count and then YouTube channel to. published video titles as well okay now if I wanted to write out information about this second Channel what I would do is I would copy this so I’m going to copy it and then paste it here and here I will say that the name is Youtube channel 2. name and then owner name is YouTube channel 2. ownername and then here as well and then YouTube channel 2. published video titles okay now if I run this program we should get information about these two channels so the first channel is this one that we already had it’s code Beauty owner is me and then this is subscribers counter and then these are three videos that I published so far I mean I published more than three videos uh but this is just an example and then here is our second channel it’s called Amy sings and then owner is Amy she has 2,000 subscribers and then she has published two covers now this here has a problem if we wanted to create a third a fourth a fifth object we would have to copy this code and then each time that we want to write out information about those channels we would have to copy this code and this really collides with a principle called don’t repeat yourself meaning do not repeat your code if you don’t really have to repeat it and in this particular situation we do not have to repeat it so how we are going to solve this problem well the first thing that I want to talk about are going to be Constructors and what a Constructor is it is a special method that is going to be invoked each time that you create an object of a specific class meaning that method is going to be called on the construction of that object so there are two rules when it comes to Constructors and the first rule is that Constructor has the same name as your class and then the second rule is that Constructor does not have a return type so let’s create a Constructor for this YouTube channel class here I’m going to say YouTube channel like this and then I’m going to put these parentheses and I’m going to put these curly brackets as well now what I want to do in this Constructor is I want to receive two parameters I want to receive two arguments and those are going to be string name and then string string um let’s let’s say owner name okay now these are two parameters that I want to pass to my Constructor and what I’m going to do with these in my Constructor is I’m going to assign these to these properties here so I’m going to say that name is going to be equal to whatever my user has passed to this Constructor so name is equal to this name here and then owner name in my class is going to be equal to this owner name that I have received in my Constructor now since since this Constructor here is invoked each time that I create object each time that it is constructed that means that at the beginning when a channel is created it has zero subscribers so I’m going to put here zero like this we do not even have to pass this value in our Constructor because when you create your YouTube channel you do not have subscribers okay now what am I going to do here is I do not need to write this code like this anymore so I’m going to delete I’m going to actually comment this code here and as you can see this is underlined it says that no default Constructor exists for class YouTube channel now what we have to do is we have to use this Constructor here that I have just created and how you do that well you put parentheses here and then inside these parentheses we are going to pass these two parameters so the first parameter is going to be the name so that is the name of our Channel and that is this name here so code Beauty like this and then a second parameter as you can see here is owner name and that was this value here so I’m going to pass that here like this and now after I have created this YouTube channel we do not need this code um anymore so I’m going to delete it okay and what we can do is we can do the same with this second channel so with this YouTube channel too so I’m going to really comment this code for a moment and then here I want to invoke a Constructor for this YouTube channel class and pass it as first value the name because we are receiving name as our first value in our Constructor like this and then then the second value that we need to pass is going to be owner name so I’m going to copy that as well and now we have successfully created this second YouTube channel okay so now I can delete this code here as well okay and now if I run my program as you can see it has written out information about my two channels the first one is code Beauty owner is me and then I have zero subscribers because I have just created my channel and we have assigned that here and then our second channel is Amy sings uh owner is Amy and she has zero subscribers as well and as you can see both of these videos published videos lists are empty because we haven’t uh really added any videos okay so how do you do that I’m going to delete this from here and then move it here like this so now we have both of our objects being created at the beginning here so what I want to do now is I want to add a couple of videos to this channel here so how do you do that well you say YouTube channel like this and then I’m going to put dot and here in this published video titles list I’m going to invoke a method push back which is going to add at the end of this list another element and that element is going to be of type string because this publish video titles is a list of strings so here I’m going to add a string and I’m going to call that video C++ for beginners like this so that is one video and then let’s add a couple more videos let’s say uh HTML and CSS for beginners and then let’s say um o op for beginners Well no let’s say C+ plus o o like this okay so we have added three videos for this first channel and then this second channel does not have videos yet so if I run my program again you can see that this first channel has three videos and then this check this second channel does not have any videos yet because we have deleted those that we previously had okay now that was the example on how you can create a constru structor and how you can use a Constructor so this here is the Constructor of this YouTube channel class and we have passed two parameters two arguments to this Constructor and then here in our Constructor we have really assigned initial values to these properties here that we have in our YouTube channel and then this here is the way that you use your Constructor so you put these parentheses and then you pass the values that your Constructor has to receive and here we have created two objects and we have done that without repeating code now what is going to happen with this here so this here and then this here is repeating code as well and in order to solve this particular Pro problem we are going to use class methods so class method is going to describe a behavior of a class and since here we are writing out uh the these attributes of our class since we are writing out information about our YouTube channels what I want to do is I want to create a method that is going to be called get info for example so that method is going to be of type void let’s call it get info like this and what I want to do in this particular method is I want to copy this code here so I’m going to cut it and then paste it here and in this particular method in this get info I want to say please write out name and then the name property we don’t need this YouTube channel object anymore because we are in the class itself okay and then here as well I’m going to delete this here and then here and now this code should work so whenever you invoke this get info method on your object it should write out all of these properties of of that object so now I can remove this code here as well so this um information about our second Channel and how am I going to get how am I going to invoke this method well I say the name of my object so for example YouTube channel Dot and then as you can see I have this get info method available here because it is public so I say get info and I invoke it like I would invoke any other function and let’s do the same for our second YouTube channel let’s say YouTube channel to get info like this and now if I run my program as you can see it has written out information about my two channels so code Beauty Sal owner and then subscribers count my videos and then info about my second Channel as well so I hope that you understood the concept behind behind a Constructor of a class and then behind a class method here we have demonstrated how you can create an object using a Constructor and then here as well so you don’t really have to repeat your code each time that you create an object and then here we have invoked a method of these objects which we have implemented here so you do not have to repeat that code as well each time that you need to get information about your object you just invoke this get info method and now our main function looks much cleaner and all the implementations of the construction of our objects and then this get info method are in this YouTube channel class so I hope that you enjoyed this video if you did give it a thumbs up and also subscribe to my channel don’t forget to hit that Bell icon and I’m going to see you in my next video bye hi everyone my name is Salina and I make it and programming related videos so if that is something that is of interest to you consider subscribing to my channel and give this video a thumbs up as well and in this particular video I want to talk about encapsulation here I have code that we have written in the previous videos of this course so if you haven’t watched those make sure to check them out I’m going to link them in the description of this video and I’m going to go over this code very quickly so that you can understand what we have written here so here I have created this YouTube channel class which has four public attributes and those are name owner name subscribers count and then list of published video titles and then here we have a YouTube channel Constructor and then this get info method as well that just writes out information about our YouTube channel and here’s the code of our Constructor okay and then in our main function we have created an object of this YouTube channel class and we have assigned it these two values for our name and our owner name and then we have as well added three videos to this published videos list and here we have written out information about our channel so if I run this code now as you can see this is how it behaves it writes out information about our YouTube channel now now what I want to talk about in this video is encapsulation and what does this principle of encapsulation says well encapsulation says that these properties here should not be public these should be private and then the way to change the value the data that you store inside these properties should be really using methods that you Expose and then you give access to those methods to your user and then using those methods obeying the rules of those methods your user can change the value of these properties okay so let me introduce a problem here so that you can really understand why we need en encapsulation so what happens if I say for example that YouTube channel so this that we have created has let’s say a million subscribers okay this is a million now we have assigned a million subscribers to this YouTube Channel and this should not be allowed if I run this program you can see that this YouTube channel has a million subscribers now but this is not the natural way to gain subscribers for your YouTube channel what you should do instead is you should give your user the ability to invoke subscribe and unsubscribe methods and then using those methods you are going to increase or decrease this subscribers counter so let’s do that let’s first hide these properties from our user so from whoever is going to use this class here so how do you hide these well you make them private so here instead of using public access modifier I’m going to use private access modifier so I’m going to say private oh private like this and then these should stay public so I’m going to put public here like this okay and then as you can see we have a problem here it says that this subscribers count is inaccessible and then this publ this published video titles as well is inaccessible meaning that we cannot access these private members of our class these private members can be accessed only within this class itself so how we are going to give our user the ability to change this subscribers counter well as I said we are going to create methods so let’s create two methods the first one is going to be void void subscribe like this and then what this method should do it should increase this subscribers counter so here I’m going to say subscribers counter like this plus plus using this increment operator we are going to increase the value that we store in this variable by one and then we are going to have as well unsubscribed method so I’m going to copy this paste it here and let’s say unsubscribe and then here I’m going to say that this subscribers count is going to be decremented so now if I I will have to comment this code here and then I’m going to delete this code here and now if I want to increase or decrease subscribers for my Channel what I will have to do is I will have to invoke one of these two methods so let’s say for example YouTube channel do subscribe like this okay and let’s invoke this method um three times for example and now if I run this program as you can see my channel so code Beauty channel has three subscribers and then let’s say for example that I haven’t published videos in a while so people decide to unsubscribe so I’m going to invoke this unsubscribe method like this and if I invoke this get info after that I should have two subscribers well oh as you can see I have two subscribers now because three people have subscribed and then one person has unsubscribed from my channel okay so we have this code here as well that was underlined meaning that it has um compile time error and it says member published video titles is inaccessible meaning that now we cannot access this published video titles list anymore because it is private now so I’m going to expose a method that is going to publish videos for me so here I want to create a method of type void which is going to be called publish video publish video like this and then here I want to add a video to my published video titles like this so I’m going to say published video titles push back and then what I want to do is I want to pass a value here which value well we are going to receive that value as a parameter in our function so here I’m going to add an argument a parameter and that is going to be of type string and let’s call it title like this and now we are going to use this title here so we are going to push this title in our push in our published videos titles okay like this now if I want to invoke this method I’m going to invoke it like this so I’m going to say YouTube channel dot publish video like this and then I’m going to do the same thing here and then here and here as well okay so now we have created these methods that we invoke and then using these methods we change these properties and these properties should be private meaning these should be encapsulated okay and now as you can see we have a channel called code Beauty and then owner is myself and subscribers is two and then these are videos that I have published so far now if you look at this unsubscribe method you will notice that it has a bug what is that bug well let’s delete these three lines of code let’s delete these subscribe method invocations and if I run my program now what is going to happen as you can see it says that my subscribers count is equal to minus one and that does not really make sense so you cannot have minus one subscriber and we are going to fix that problem if we put here inside this unsubscribed method a check so we want to check if our subscribers count is greater than zero and only in that situation if that subscribers count is greater than Z zero only then we can decrease this subscribers count value so if I run my program now as you can see we have invoked this unsub subscribe method but we still have zero subscribers and now we have fixed that bug that we had because if no one has subscribe to our Channel then no one can unsubscribe from it okay so that was a bug that I wanted to fix and then what you can do here because here we have exposed these three methods that really manipulate the values that are stored inside these properties and then these two properties there is no way to change them outside of this class so what you can do for dam for example is you can create a getter and a Setter meaning a method that that is called for example get name and that method is going to return you the value that is stored inside this name variable and then a set method meaning set name method that is going to receive um parameter which is going to be called name for example and inside that set name method you are just going to change the value that is stored inside this name property and then you can do the same for this owner name uh as well so you can create a get and a set method so let’s go over this encapsulation rule one more time so encapsulation rule says that all of these properties should be private meaning they shouldn’t be accessible outside of this class and you do that by making them private so you put this private access modifier here and then how do you change the values that you store inside your properties well you expose a public methods that are going to change the data that you are storing inside your properties and here we have created these three public methods that are going to change the data stored inside our subscribers count uh property and then inside our published video list property here so you can for these two properties again you can create getter and Setter method and if some of you do that please put that code in the comment section and I’m going to review it so if you enjoyed this video give it a thumbs up and don’t forget to subscribe to my channel and hit that Bell icon as well and I’m going to see you in my next video bye hi everyone my name is Salina and I make it and programming related videos on my channel so if that is something that is of interest to you consider subscribing and give this video a thumbs up as well and in this particular video I want to talk about inheritance so here I have my visual studio and here I have some code that we have written in the previous tutorials of this course so if you haven’t watched those make sure to watch them and now I’m going to go very quickly over the code that we have here so I have created a class that is called YouTube channel and that class has four private properties name owner name subscribers count and then published video titles and then we have a couple of public methods as well we have a Constructor which just assigns initializes these variables here and then we have get info method that just writes out information values that are stored inside these properties here and then as well we have subscribed and unsubscribe methods our subscribe method increases our subscribers counter and then our unsubscribe method decreases that subscribers counter but first we have to check if that subscribers count is greater than zero so those would be subscribe and unsubscribe methods and then we have this publish video method as well that just adds a new item adds a new title to this published videos list okay now what is going to happen if I want to create another type of YouTube channel a specific type of YouTube channel which is going to be for example um cooking YouTube channel so I should copy these properties right well that can be one approach but the quicker and better approach is going to be to inherit this YouTube channel class so let’s do that let’s create another type of channel so let’s create another class let’s say class and then let’s call it cooking YouTube channel like this okay now I have created a class that is called cooking YouTube channel and in order to inherit this YouTube channel class what I’m going to do is I’m going to put this column sign and then I’m going to say public you YouTube channel like this and in this way my cooking YouTube channel is going to inherit my YouTube channel and that means that my cooking YouTube channel is going to have everything that my YouTube channel has now this public access modifier means that whatever is public in this class here it is going to be public here as well so in this derived class and one very important thing is is to know that this class is called Base Class so the one that you inherit from that is base class and then the derived class is going to be this one here so the one that inherits from the base class is called derived class and in this particular situation our cooking YouTube channel is derived class now what is going to happen if I want to create for example an object of this cooking YouTube channel so I’m going to say cooking YouTube channel and let’s call it YouTube channel like this okay now as you can see it says that default Constructor of cooking YouTube channel cannot be referenced now that is because we do not have a Constructor for this class here so let’s create one let’s create a Constructor so I’m going to copy this name and then add these parentheses okay and now if I hover over this it says that the Constructor is inaccessible so we still have an error but we have a different error which means that we are making progress so because this Constructor is inaccessible I will have to make it public to make it accessible outside of this class here so I’m going to say public okay and now my uh Constructor is going to be accessible but there is another thing that we have to do and that is going to be inside this Constructor we have to receive properties that we are going to initialize in our Constructor and those are going to be these two properties name and owner name so here I’m going to say that my Constructor receives two properties so string name and then string owner name so the owner of that channel and what I’m going to do when I receive these two properties I’m not going to initialize them here in my Constructor because I’m inheriting from a class that already knows how to construct how to initialize these two particular properties so I’m going to call the Constructor of that class so I’m going to call the Constructor of this YouTube channel class so here I’m going to put this column sign and then I’m going to invoke its Constructor so I’m going to say YouTube channel and then I will pass these two parameters here so I’m going to say name and then owner name like this and now our Base Class our YouTube channel class is going to construct to initialize actually the value of these two properties and as you can see here we have an error that asks us to pass these two values to our Constructor so we are going to pass two parameters the first one is going to be the name of our channel so let’s say that that is going to be for example Amy’s kitchen like this and then owner is going to be um girl named Amy let’s put that here as well okay now after I have created an object of this cooking YouTube channel what I should be able to do is I should be able to access all of these public methods that my base class has so all of these methods from my YouTube channel class should be available for my uh cooking YouTube channel so here I’m going to say YouTube channel Dot and then as you can see these are available so get info publish video subscribe unsubscribe let’s write out info about my channel like this and if I run it now well you you can see that we have Amy’s Amy’s kitchen Channel owner is Amy it has zero subscribers and it has no videos as well so let’s publish a couple of videos for Amy Amy’s kitchen channel so here I’m going to say okay before I this get info function I’m going to say YouTube channel Dot and then let’s say publish video of for example apple pie like this this and then let’s publish another video let’s say for example chocolate cake like this and uh now if I run this program as you can see we have oh we have two videos and let’s as well say that people like these videos so they decide to subscribe to Amy’s kitchen channel so I’m going to say YouTube channel do subscribe so uh for example two people decide to subscribe to her Channel and if I run my program again you can see that now we have two subscribers as well so we have been able to invoke all of these methods that are implemented in our Base Class so here from the object of our derived class so from the object of this derived class class here now this derived class this cooking YouTube channel can have its own members meaning things that are specific for this class only so let’s say for example that we want to create a method that is going to be called uh for example practice so I’m going to say void practice like this and then what this method should do it should just make our user that has this cooking YouTube channel it should say that this user is practicing cooking and then learning new recipes and things like that so I’m going to say see out like this and that let me copy this part of the code because I don’t want to make a typo like this so it says that uh our YouTube Channel’s user is practicing cooking learning new recipes and then experimenting with spices cuz I guess that’s something that you should do if you have a cooking YouTube channel Channel and let me add endline here as well like this so now if I decide to invoke this method this method is going to be available only for objects of this cooking YouTube channel so I’m going to say YouTube channel like this and then let’s say practice like this now um let me very quickly change the name of this YouTube channel object because I want to create another object that is going to be of uh this YouTube channnel type and I want to call that YouTube channel so here I’m going to say um cooking YouTube channel and I’m going to paste that name here and then here and here here as well okay now we have named this object cooking YouTube channel and if I run this program you can see that at the end it says practicing cooking learning new recipes experimenting with spices is now as I already said this practice method should be available only for the objects of this cooking YouTube channel class so that means if I decide to create an object of this class here this Base Class that class is not going to have this practice method and let’s prove that very quickly so here I’m going to create an object of YouTube channel Class Type and let’s call that object YouTube channel that’s why I changed the name name of this object like this and let’s say that that is going to be my channel for example um code Beauty like this and then let’s say that owner is my name Salina so now if I try to access this practice method on my YouTube channel so I press dot you can see that that method is not available for this Base Class it is available only for this cooking YouTube channel class because this practice is very specific method meaning um this code Beauty Channel which is oriented to programming and it does not really benefit from learning uh recipes and experimenting with spices practicing cooking and things like that so this channel should probably have some other way of practicing uh because it is different type of channel so I’m going to delete this code here okay and let’s repeat this one more time so we have created a derived class which is called cooking YouTube channel and we have inherited everything that our YouTube channel class has by saying public and then the name of our Base Class and this public access modifier is going to allow us to have whatever is public here to have that public here as well and then we have created a Constructor for our cooking YouTube channel and in that Constructor we receive two parameters name and owner name and since our Base Class Constructor knows how to initialize those two we have here invoked this Base Class Constructor and then here we have created as well a method that is called practice and that method just says that our user is practicing cooking and he is learning new recipes and experimenting with spices now there’s one more thing that I want to show you and that is going to be to Let’s create another object of this cooking YouTube channel and that is going to be uh let’s say cooking YouTube channel to and let’s call it um John’s kitchen like this and owner is going to be for example John now what is going to happen if I say for example that this second YouTube channel so this cooking YouTube channel to John’s YouTube channel is practicing I’m going to um comment these two because I don’t need them and if I run my program now you can see that it says two times practicing cooking learning new recipes experimenting with spices and then the same line here so you cannot really differentiate between which which one is Amy’s Channel and which one is John’s channel so in order to make that a bit more understandable I’m going to add a property here so here I want to add the name of the owner of this channel so here I’m going to say let me copy this property like this so owner name and then let’s say that that owner is practicing cooking learning new recipes experimenting with spices and so on but as you can see this this property here is not accessible it says that member owner name is inaccessible and why is that the case why is it inaccessible because it is private and if you remember private members can be accessed only within that class and then public members can be accessed from outside of that class but what happens if you want to have for example a certain property to be accessible in in the derived class now there is an access modifier for that as well so that is going to be protected access modifier so I’m going to say here protected like this and then I’m going to move this owner name to my protected area like this so now this owner name property should be accessible in derived classes as well and as you can see the error has disappeared so now if I run my program you can see that it says that Amy is practicing cooking learning new recipes and experimenting with spices and then this second line here says that John is practicing cooking and learning new recipes and experimenting with spices so now we have made a difference we have specify the name of our owner of the channel and we can understand what the code is doing um a bit more I hope that you understood what is inheritance and how it works in C++ and if you did please like this video don’t forget to subscribe to my channel and click that Bell icon as well and I’m going to see you in my next video bye hi everyone welcome to my channel my name is Salina and I make it and programming related videos so if that is something that is of interest to you consider subscribing to my channel and give this video a thumbs up as well and in this particular video I want to talk about polymorphism now the first thing that I want to do is I want to explain what is polymorphism polymorphism describes the ability of an object for example to have multiple forms now that means that you can have two or more objects that inherit from the same Base Class those objects can have the method that has the same name but different implementation meaning different behavior and I’m going to demonstrate that on an example now here I have some code that we have written in my previous courses so if you haven’t watched those make sure to do so the links to those videos are going to be in the description and I’m very quickly going to go over this code so here I have created a class that is called YouTube channel that class has three private prop properties name subscribers count and then published video titles and then it has one protected property which is owner name now um this private properties these are available only in this class and then these protected properties these are available in derived classes as well and then here we have public methods as well and this here is our Constructor so it just initializes values of um these properties I’m going to collapse death and then here we have get info method with which just writes out information about our YouTube channel and then these subscribe and unsubscribe methods these just increase or decrease the the number of our subscribers let’s collapse that and then publish video method it just um adds another video to this published video titles list so that would be our YouTube channel base class and then here we have cooking YouTube channel which is a specific type of YouTube channel that inherits from this Base Class here and that cooking YouTube channel has its own Constructor which is this one here and here we have just invoked the Constructor of our base class and then here we have implemented a method which is called practice and it says that when you practice and you have a cooking YouTube channel you will have to be practicing uh cooking and then learning new recipes and experimenting with spices now what I want to do is I want to create another derived class so I’m going to copy this okay and then this derived class should be called for example what let’s paste the name here so singer YouTube channel and I’m going to paste the name uh here as well on my Constructor so this is going to be a YouTube channel about singing now as you can see this singer’s YouTube channel has this practice method as well but this implementation is not right for my singer YouTube channel because if you’re a singer you are not going to benefit really from practicing cooking and then from learning re PES and experimenting with spices but what you should do instead is you should practice something else so I’m going to copy that so that I don’t make a typo like this so someone who is trying to make a singer’s YouTube channel is going to take singing classes and then learning new songs and then he should as well be learning how to dance because I believe that singers should know how to dance as well okay so now we have implemented this singer YouTube channel and as you can see as I already demonstrated it has this same method which is practice but this method has different implementation than this one and as you can see here this is the implementation of our practice method on our Cooking Channel and then this here is the implementation on our singer YouTube channel so what I want to do now is is I want to create this singer’s YouTube channel here we already have cooking YouTube channel so it is a video it is a code from one of my previous videos and then what I want to do is I want to create um singer YouTube channel so let’s call it um Singers YouTube channel and let’s say that it is going to be called for example John sings like this and then owner is going to be a guy named John like this okay now after I have created this cooking YouTube channel and then this singer YouTube channel you can probably call it singing YouTube channel or something like that uh this is the best name that I could come up with okay so now what I want to do is I want to invoke methods on these two classes and the methods that I want to invoke are going to be these two so practice and then this practice method as well so here I’m going to say cooking YouTube channel do practice like this and then let’s invoke the same method for my singer YouTube channel like this and now if I run my program as you can see it says that Amy is practicing cooking and then John is taking singing classes and learning new songs and learning how to dance I can imagine that okay now after I have invoked these two methods you can really see oh I have stopped my program I’m sorry so here you can see that this cooking YouTube channel has invoked its own method so this cooking YouTube channel has invoked the method that has been implemented in this cooking YouTube channel class which is this one here and then this invocation so this singer YouTube channel when you invoke practice method on that this method here is going to be invoked so this method that is implemented in singer YouTube channel class now let’s add another thing and that is going to be here in this practice method and then in this practice method as well what I want to do is I want to say that each time that our user practices cooking and then practices singing what is going to happen is the quality of that YouTube channel is going to increase so in order to track that quality content rating I’m going to create a property and that is going to be here in this YouTube channel in this Base Class so I’m going to make that property uh protected protected because I want to have it accessible in my cooking YouTube channel and then in my singer YouTube channel as well so I want that property to I want to access that property from my derived classes and because of that I’m going to make it protected so here I’m going to say int and let’s call it it content quality like this okay and initially I want to set the value of this content quality variable in this Constructor here I want to set it to zero like this because I want to say that when you create your YouTube channel this Constructor here is going to be invoked and you are going to have zero subscribers and you are going to have a zero knowledge about content quality so your rate content quality rate is going to be zero so let’s close that and then what I want to do here in this practice method is I want to say each time that you practice your content quality should increase so let’s increase that variable content where is it content quality Plus+ so I’m going to increment that content quality and then I’m going to do the same here like this now let’s say for example that my um this singer here John he’s going to practice a lot so he has practiced five times more than Amy did so if I run my program now you can see that John is practicing and then again and again and again so he is practicing a lot and Amy is not really so what do I want to do with this content Quality Property well let’s say that I want to implement another method and that method is going to be as well implemented here in this Base Class and that method is going to be called uh check analytics because that check analytics method should be available for all YouTube channels so that is not something that is specific for this cooking YouTube channel only or for this singing YouTube channel so singer YouTube channel but that method should be available for all YouTube channels and because of that I’m going to implement it in this Base Class so let’s say void check analytics like this okay and now what I want to do in this check analytics method is I want to use this property this content Quality Property in a following way so I want to say if content quality is less than five I want to write out a message to my user so I want to say see out and then let’s write out the name of this YouTube channel like this and then let’s add um a message which is going to say let me copy that okay this is going to say that this channel has a bad quality content because this content quality has a rating that’s that is less than five and let’s add in line and then what is going to happen if this content quality is not uh less than five so if it is equal to five or greater than five I’m going to put else block here and what I want to say here okay is that this channel has a good content great content actually okay like this now what am I going to do with this check analytics method well I’m going to try to invoke it here but the way that I want to try to invoke this um this method that we just implemented is going to be in a following way so there is one very interesting thing when it comes to polymorphism and that thing is related to pointers um at this point I haven’t made videos about pointers on my channel but if you’re watching this video sometime in the future sure then those videos are probably available on my channel so make sure to look for them on my channel and then in the description of this video as well so let’s create a pointer and that pointer is going to be a pointer of our Base Class so a pointer of type YouTube channel okay like this and let’s call it YouTube one and what I want to do is I want to assign to this pointer here address of this cooking YouTube channel and you can do that you can assign to a pointer of a base class an address of derived class so I’m going to say here please to this pointer assign address of this cooking YouTube channel class like this and then what I want to do is I want to create another pointer let’s call it YouTube 2 and then to this YouTube 2 pointer I want assign the address of my singer YouTube channel like this so one more time a pointer of Base Class can point to a variable of derived class now what I can do using these pointers is I can invoke method that I have just created which is this one here so check analytics so let’s do that let’s say YouTube channel one and then um let’s invoke this method let’s say check analytics like this and if you just noticed it has changed my DOT to this symbol here because this is used when you want to invoke methods using pointers so I’m going to copy this again for my second YouTube channel like this and now if I run my program as you can see our John has been practicing a lot and then Amy has been practicing only one time so here after I have invoked these two methods this first method says that Amy’s kitchen has bad quality content because she hasn’t been practicing enough and then after this YouTube channel to check analytics you can see that it writes out this message that John sings channel has great content because he has been practicing a lot as you can see here okay so here we have used polymorphism in order to implement this practice method in our cooking YouTube channel and then in our singer YouTube channel so implementation of our singer YouTube channel practice method is here and then for our cooking YouTube channel our practice method looks like this and we have done that uh thanks to the polymorphism so different implement ations but the same method name and then I have demonstrated here how you can use pointers to point to an object of derived class and you can store that in a pointer of Base class and then we have invoked this check analytics methods using these uh pointers of Base class so I hope that you enjoyed this video if you did give it a thumbs up up and don’t forget to subscribe to my channel click the Bell icon as well and I’m going to see you in my next video bye hi everyone welcome to my channel in this video I want to talk about pointers so I will go straight to the point uh pointers are very important Concept in C++ and they have many uses in C++ now pointers are not limited only to C++ they exist in other programming languages as well but in most of those programming languages they are really hidden they work behind the scenes so you cannot see them and you cannot use them yourself but it’s C++ you can use them and you can create your own pointers and they can be pretty powerful if you know how to use them but they can get quite confusing as well if you don’t understand them well so the first thing that I want to explain is what are Pointers so we already have explained the concept of a variable and you should be familiar with that that so we said that a variable is just a container so a container that stores certain value now a pointer is container as well but instead of storing value pointer stores an address so a memory location and let me show you how pointers work in Visual Studio let’s create a variable of type int and I’m going to call it n and assign it a value of five and let’s write out this n like this so nothing new here we are already familiar with this and if I run my program as you can see we get this value of five so that was expected now as I already said this N is a variable and that means that it is a container which is storing certain value now because it is a container that means that it has its address inside memory so it has its physical location so how can we get that location how how can we check which address this n has so in order to do that you use this ENT symbol like this so you put it before your variable name and that should give you the address of that variable so if I run my program now as you can see now we have an address um and this is the address of our n variable so this is its physical address where this value of five is stored and because this is pretty hard for humans to remember this is just a random numbers and characters because of that we use meaningful names and we access these values that we store in our memory using these meaningful names which are our variables so I’m going to close this now and what I want to show you here is I want to show you how can you create a pointer that is going to hold this address of our r n variable so in order to create a pointer you give it a type first so you say int and then in order to indicate that you are creating a pointer you use this star symbol and then you give it a name so let’s call it PTR pointer and I’m going to assign it the address of our n variable so I’m going to copy this and paste it here okay now our pointer is holding the address of our n variable and in order to prove that I’m going to write out the value of my pointer like this so as expected we have this first line here which is writing out the address of our n variable and then this second line of code is this line here and as you can see we have written out the value of our pointer and that is the same address as this one here here which means that our pointer really is storing the address of our n variable now you may ask how can I access or can I access the value that is stored on that address using pointers and the answer to that question is yes you can and in order to do that in order to access the value that is stored on this address that your pointer is holding you have to dreference your pointer so how do you do that well let me copy this so as you already have seen this line of code here is going to write out the address and in order to write out the value on that address you dreference the pointer and in order to do that you add this star symbol before your Pointer’s name so if I run my program now as you can see in this last line of code we have the value of five which is actually the value that is stored on this address here so let me show you one more thing what I want to do is I want to change the value that is stored on this PTR address so on this address that our PTR pointer is storing so how am I going to do that I’m going to say again star symbol and then PTR and this here means please access this memory location so whatever I’m going to assign here is going to be stored on that memory location and what I want to assign is for example value of 10 like this so now if I copy this line of code and then paste it here and if I run my program again we have this value of 10 stored on this address here and one interesting thing as well is that if we try to write out the value that our n holds now like this if I run my program as you can see our n holds the value of 10 as well even though uh we have never said that n has the value of 10 but we have stored the address of our n in our pointer and then we have D referenced our pointer meaning we have changed the value on that address here in this 11th line of code here so that’s why our n holds value of 10 now one very important thing to keep in mind is that your pointer has to be of the same type like the variable that it is pointing to so let’s close this so as I said this integer pointer is pointing to an integer variable so our n is of int type and the same way would be if we created a float pointer it would have to point to a float variable and then chart pointer can point only to a Char variable double bull um and so on so pointer and the variable that that pointer is pointing to have to be of the same type okay so that means that if I try to change the type of this n variable to float for example like this so if I say float immediately we get an error here and the error says a value of type float pointer cannot be used to initialize an entity of type end pointer meaning you cannot assign address of a float type to pointer of int type okay so that is the error that we have here and I’m I’m going to return this to int okay and as you can see that error has disappeared because now our pointer is pointing to the same type so to the variable of the same type that that pointer has so int pointer pointing to an INT variable one thing that beginners very often try to do is the following so they say okay let’s create a pointer so int let’s give it a name ptr2 so pointer like this so I have created a pointer right so let’s dreference this pointer and assign it a value so I’m going to say please D reference PTR 2 and assign it a value of 7 for example now this code here has a problem problem and if I run it if I say build solution actually as you can see it says uninitialized local variable ptr2 used this means that this ptr2 so this pointer to does not have an address so where should it store this value of seven if it does not have an address and the easiest way right now to solve this problem is going to be to create a variable and to give the address of that variable to our ptr2 pointer so I’m going to say int V this variable has to be of the same type as our pointer as we already said and then I’m going to say here our ptr2 is going to hold hold the address of our V variable like this and now we shouldn’t have this problem anymore so if I build my code again as you can see one succeeded so the problem has disappeared and let me write out the value of this V variable so I’m going to say V is equal to and then let’s write out the value of this V and if I run my program as you can see it says that V has the value of seven because we have assigned it here by D referencing our pointer that is holding the address of our V so you may say now okay Salina I understand this but this seems a little bit too much why would I create a pointer just to assign a value to a variable and the answer to that question is you don’t this is not the type of problem for which pointers were created in C++ so this there are different problems that pointers solve in C++ and this here is just a demonstration of what are Pointers and how can you create your own pointers now examples of some of these other problems that pointers solve is you can use pointers in order to pass values by a reference to a function and then you can use them to return multiple values from a function which is an interesting one uh you can use pointers in combination with arrays as well uh you can use them for dynamic memory allocation and then if you’re familiar with oop objectoriented programming you can use a pointer of a base class in order to access a object of derived class and then there is this concept of smart pointers which we are going to cover in the future so I believe as well that I have mentioned some of these things in some of my videos but I plan to make um dedicated series to pointers where we are going to talk only about pointers so stay tuned subscribe to my channel um hit that Bell icon as well so that you are notified when I publish my next video and if you like this one give it a thumbs up thank you for watching and I’m going to see you in my next video where we will be talking about pointers bye hi everyone welcome to my channel in this video I want to talk about void pointers now in the previous video of this playlist I introduced you to pointers in general so I explained what are Pointers and how you can create your own pointers and I said that a pointer is a special variable that can hold an address and I said as well that a pointer can hold only the address of a variable that is of the same type as that pointer which means an integer pointer can hold the address of an integer variable and then a character pointer holds the address of a character variable float pointer of a float variable and so on but there is an exception to that rule and that is a void pointer and a void pointer is a special type of pointer that can hold the address of a variable of any other data type so a void pointer can hold the address of a float variable or an INT variable or a Char bull struct whichever one you pass to that void pointer but a void pointer has a limitation as well and that limitation is that you cannot directly D reference a void point so in order to demonstrate this I’m going to create an example with the knowledge that we already have so using only integer and character and Float pointers that we are already familiar with and then I want to introduce a void pointer in order to solve that problem so that you can see how void pointers are used so let’s jump into our Vis Visual Studio here I want to create a variable um and let’s make it of int data type so I’m going to say int and let’s call it number like this and I’m going to assign it a value of five for example now what I want to do with this number variable is I just want to write it out and because we are working with pointers let’s play with pointers some more so I want to write out this variable using a function that receives a pointer let’s do that so that function is going to be of return type void and let’s call it print number like this and then here this function is going to receive an integer pointer and we are going to call it uh number PTR so number pointer okay now what this function here should do is it it should just print out the value that this number pointer is storing so actually the value that is stored on the address that this number pointer is holding so in order to do that we have to the reference this pointer so I’m going to say star symbol and then put the name of this number pointer and let’s add an end line as well now this function is finished and it is writing out the value that is stored on the address that we passed to it and we have to pass it the address of an integer variable so if I invoke this print number function let’s say print number as I said since it is receiving a pointer we have to pass it an address and that is going to be the address of this number variable so let’s say m perent number so this here is going to give us the address of this number variable okay and now if I run this program as you can see this function here has printed out value of five which is the value of our number okay now what happens if I want to create a k character variable and then print out a character variable as well so let’s do that I’m going to say Char let’s call it letter and let’s assign it a value of letter A okay and now in order to print out this character using this same approach I will have to create another function because this one here receives an integer pointer and in order to print out a character we would have to create a function that receives a character pointer so let’s copy this function here and I’m going to call it print letter like this and then this function is going to receive a character pointer okay and that pointer is going to be called Char PTR and then here I just want to write out the referen value of that Char PTR so let’s invoke this print letter function let’s let’s pass it the address of this letter variable that we have created here and now if I run this program as you can see we have five for this first function and then a for this second function which means that these two functions are doing its job but what happens if I want to print out a floating Point number and then a double and then a Boolean value and a stct value in order to do each one of those I would have to to create a function that receives that specific data type pointer but we can solve that same problem using a void pointer because as we already said a void pointer can point to a variable of any data type so let’s do that let’s create a function that is going to print out any data type so that function is going to be of return type void and let’s give it a name print because it is generic it is going to work with all data types I’m going to give it name of print and as we said that function is going to receive void pointer and let’s call that pointer PTR okay now because this void pointer can point to a variable of any data type we will have to keep track of which data type we have passed inside this void pointer and in order to do that I’m going to use another parameter here and that parameter is going to be of type R and I’m going to call it type so how this type parameter is going to be used well in a situation where we pass an integer pointer to this print function here this type parameter is going to have a value of I in a situation when we pass a character pointer to this void pointer here in this type parameter we are going to pass a value of c and then if we pass a float pointer here here we are going to store an F and then if we pass a double pointer here this type variable should store a letter D so that we can know how we are going to dreference this PTR pointer so the first thing that we have to do is we have to check what this type variable is holding so in order to do that I’m going to use switch case like this you can use if else as well if you want so here I’m going to switch on this type variable like this and what I want to do here is I want to say in the case that this type variable is holding the value of I that means that this here is an integer pointer so here I’m just going to leave a comment for now so I’m going to say handle int pointer like this and then the other situation is going to be in the case that this type variable is holding the value of C that means that here we have passed a character pointer so I’m going to leave another comment as well so here I I’m going to say handle Char pointer okay now let’s explain how we are going to handle this integer pointer and then this character pointer as well well as we already said since a void pointer cannot be dereferenced directly but we first have to cast it into a specific specific data type so into an integer pointer or into a character pointer in this particular situation I’m going to do that so here I’m going to say in the case that our user has passed an integer pointer here I will have to cast this void pointer into an integer pointer first so how do you do that well you say please this pointer here so this PTR cast that into an integer pointer so this expression here is going to cast this void pointer into an integer pointer so in these parentheses here we are going to have an integer pointer and in order to access to the address that an integer pointer is storing and write out the value that is stored on that address we dreference that pointer and for that we use this star symbol so now here we have the value that is stored on this integer pointer and I’m going to write out that value like this and let’s add endline as well so this here writes out the value of an integer pointer so let’s copy that and then paste it here and here what I want to do in this C situation is I want to cast this void pointer into a character pointer so Char pointer and then after I have character pointer here I ID reference that and then this line is going to write out the value of our character okay so now if I invoke this print function I should get the value of this number and then of this letter as well using only this print function so let’s comment these two for now and let’s invoke our print function so I’m going to say print and then the first thing that it receives is going to be DX address and in this particular situation considering that this is a void pointer we can pass it the address of any data type so we can pass it the address of a integer variable or of a character variable or of a floating Point variable and in this situation we have integer variable and then character variable so let’s use these two so let’s pass here the address of our number that oh that is going to be the first parameter and then the second parameter is going to be the type and considering that we have passed the address of an integer let’s pass the value of i as our second parameter here okay and then I’m going to copy this function one more time and this time I want to pass it the address of our letter variable and considering that that is a character here as a second parameter I’m going to pass C now I’ve just not notice that something is missing from our switch case and before I say what it is please write your idea write your answer in the comments down below so what we are missing in these two cases is break at the end so here I’m missing a break like this and then here as well okay so now we have completed our switch case and if I run my program now as you can see for this first line we get the value of five which is our integer so this print function has printed the value of our integer and then in this second line we have printed out the value of a character and we have done that using this print function which receives a void pointer and then it receives a Char uh variable which is called type and we use that Char variable in order to differentiate which data type we are storing inside this void pointer because as I already said a void pointer can point to a variable of any data type but it cannot be de referenced directly so for that we are using this type parameter to check which data type is stored inside this pointer here so now you have an idea on how to use void pointers but I would actually advise you to be very careful when using void pointers why because your compiler in this particular situation does not have a way to tell you hey you are trying to cast a void pointer which is actually an in pointer into a character or vice versa if you’re doing that your compiler in this situation here does not have a way to know if you’re are making an error or not because inside a void pointer you can store the address of any variable so of a variable of any data type and then you can try to cast that void pointer into a pointer of any other data type which means for example in this particular situation here we are passing an integer so this number here is an integer which means that here for this line of code we are receiving an integer pointer okay and then in this case here we are trying to cast that into an integer pointer and that is okay but if we accidentally make a mistake here and we try to cast that into a character pointer for example like this our compiler Now does not have a way to know that we are making a mistake here and if we run our program look at this we get this undefined symbol here which is what is this you know this is not the expected behavior of our program and we did not get a compile time error which means that this here is is completely valid so your compiler is not going to tell you that this here is an error but it actually is a logical error and those type of Errors so logical errors are much harder to find inside programs and this here is a small program and it is kind of easy to find an error in a program that has 20 lines of code but if you had a logical error in a program that has 20,000 L lines of code for example you would have a very very big problem so again I strongly advise you to be very careful when you are using void pointers because as you see compiler is not uh reporting an error for this situation here but but this actually is an error so I’m going to return this to an integer pointer okay so I hope that you enjoyed this video and uh that you learned something new and if you did give it a thumbs up subscribe to my channel and thank you for watching I’m going see you in my next video bye hi everyone welcome to my channel in this video I want to talk about pointers and arrays and if you watched the first video of this playlist you remember that I said that one of the common uses of pointers is using them with arrays so in this video I want to demonstrate how that works so let’s jump straight to our visual studio and let’s create an array of type in and I’m going to call that array lucky numbers like this and let’s say that I have five lucky numbers for example and those are 2 3 5 7 9 oh that’s five numbers already okay so these here are my lucky numbers and now I want to show you one thing so what is going to happen if I say for example see out lucky numbers and let’s add and l so what is going to be written out if I write out just the name of my array let’s check that if I run this program as you can see we get an address but what is this address this address here so the name of our array is actually the address of the first element of that array and in order to prove that let’s write out the address of the first element of this array to check if these two are going to be the same so here I want to write out the address of the first element which is the element with index zero so now if I’m telling the truth these two should be the same so if I run my program as you can see indeed we get the same address which means again the name of the array is the address of the first element of that array now that means that this lucky number’s name behaves as a pointer and these square brackets here are behaving as a operator for D referencing so if I say for example see out lucky numbers of two I’m going to get the element that has index two so this here is going to be the first address and then it is going to add two more addresses to that element and we are going to get the value that is stored there so lucky numers name is the address of the first element it is going to add two more addresses to that so one two so this line of code here is going to give us the value of five let’s add endline and run our program in order to demonstrate that and as you can see indeed we get the value of five now there is another way to do this same thing here and that is going to be the following way so I can say see out please write out this lucky numbers which as we already demonstrated is the address of this first element so I’m going to put that here and then I can use arithmetic operators on this so I can say please add to this lucky numbers two more address spaces and then the reference this so we use star symbol for that and then I’m going to add end line and these two lines of code so this one here and this one here should behave the same so if I run my program now as you can see we get the same value so these two lines of code are doing the same thing which means that this line of code here is using these square brackets in order to the referentie the element with that index which is index 2 and we know that the indexing starts with zero so 0 1 2 and we get the value of five and then this second line of code here uses this star symbol in order to differentiate this expression here and what this expression here says it says lucky numbers which is the address of the first element as we demonstrated here so please use the address of the first element and then add two more address spaces to that so the address of the first element if I add two more to that it’s going to be the address of one two so the address of this one here and then if I dierentiate that I get this value which is stored on that address so these two lines of code are writing out the same thing so let me very quickly show you how you can enter the values for this array and then write them out because here we have hard hardcoded value so I’m going to delete this and um I’m going to comment these two lines of code as well no actually I’m going to comment all of these because we don’t need them anymore but I’m going to leave them for you so that you can um see how these are used in order to deeri um your array so as I said we want to enter values for our array now so in order to do that I’m going to use for Loop so I will say four and then our for Loop starts uh with I equal to Zer because that is the index of our first element and then considering that our array has five elements and the last one has index of four we are going to run our four Loop while I is less than or equal to four and in each iteration we are going to increment the value of our I okay and in order to enter values for our array let’s write out a message so I’m going to say see out number so please enter a number that is going to be the message for our user and then I’m going to input a value from my console into lucky numbers of I so this here means please enter the value into our lucky numbers array to element that has the same index that our I holds in that iteration so in the first iteration index zero in the second iteration index one and then in the third iteration index two and so on so this for Loop here is going to help us to enter the values into our lucky numbers array and in order to show that I’m going to put here a break point and that means that our program is going to stop its execution when it comes to this line here so if I run my program as you can see it asks me to enter number so I’m going to say 2 5 7 9 and 13 so those were five numbers that we had to enter for our lucky numbers array and if I press enter one more time as you can see our program has been stopped in this line of code here and if I hover over my lucky numbers here we have values that we have entered for our array so value of 2 5 7 9 and 13 which are the values that we have entered here so I’m going to stop my program now please stop okay and now what I want to do is I want to use this other approach to write out the numbers that this lucky numbers array is holding so let’s use another for Loop I’m going to copy this one okay and then what this second for Loop is going to do it is just going to write out these numbers but but okay let’s use this approach for now so I’m going to just change this to see out and then use these other redirection signs and after each number I’m going to add an empty space okay like this and instead of using this approach here so instead of uh using these square brackets in order to deeri uh the element on that position let’s use this approach here so I’m going to say please use lucky numbers so which is the address of the first element and then to that I want to add the value of my I so plus I like this and this is going to move okay so this expression here is going to help us to access all of the elements of this lucky numbers array so from the one that has index zero until we come to the one that has index for and because we don’t want to write out addresses because this here is going to give us the address but we want to write out the values that are stored on those addresses we will have to dreference this expression here so for that I will use star symbol and I’m going to remove this breakpoint now and I’m going to start my program to see what is going to happen Okay and let’s enter 2 3 5 7 9 19 and as you can see we get values of 2 3 5 7 and 19 which we have entered okay let’s stop this program now and there is one more thing that I want to show you what is going to happen if I change this max value from four to five like this so what is going to happen in this particular situation let’s run our program and enter numbers again so 2 5 7 13 15 okay as you can see now here we have these five numbers that we have entered so 2 5 7 13 15 those are the ones here and then the last one is something that we do not recognize what is this this is some junk number that we definitely have not entered here so this number here is something that does not belong to our lucky numbers array and here we have accessed someone else’s memory base so we have this result because we changed max value from four to 5 here and as we already know our lucky numbers has five elements the last one having the index of four which is this one here and then here we added one more iteration so now we are trying to access the element with index five and that element with index 5 does not belong or does not exist in our lucky numbers array so so this element here this is memory location that belongs to someone else and we accessed that trying to deeri the pointer to the element that is Sixth Element so we have five elements in our lucky numbers array and then if we add one more address space to that we get this here which is memory location that belongs to someone else and if we just randomly change and access memory locations that do not belong to us we can cause very very big problems so I advise you to be very careful when iterating through your arrays and to access only memory locations that belong to that array that you are iterating so in the case that your array has five elements that those are going to be from zero to four so indexes from 0 to four in the case that your array has 10 elements for example those are going to be indexes 0 to 9 and so on so again be very very careful to not access memory locations that do not belong to you so I hope that now you have an idea on how pointers and arrays go together and as well we have seen some of the potential problems that can happen if you are not careful enough when working with pointers and arrays so again I advise you to be very careful uh when working with pointers and arrays and and not access memory locations memory addresses that do not belong to you so thank you for watching this video If you enjoyed it if you learned something new give it a thumbs up and subscribe to my channel hit that Bell icon as well you can follow me on my other social media if you want links for those are going to be in the description of this video thank you for watching and I’m going to see you in my next video bye hi everyone welcome to my channel in this video I want to explain how you can use pointers in order to return multiple values from a function so I said in the first video of this playlist that using pointers to return multiple values from a function is a very common use for pointers so in this video I want to demonstrate how that works so here we are going to create an array of numbers and then first I want to create two functions and one of those two is going to return me the smallest number in that array and then the other one is going to return me the largest number in that array and then in the second part of this video I want to show you how you can use pointers in order to get both smallest and largest number using one function only so you can return both of these numbers so Min number and Max number using only one function and that is going to be with the help of pointers so let’s start with this example as I already said uh I’m going to create an array of numbers so um those are going to be numbers of type int and let’s call this array numbers like this and it is going to be array of five numbers and let’s assign him values of for example 5 4 um – 2 29 and 6 for example so those are going to be my numbers okay and now let’s create a function that is going to return the smallest number of this array so I’m going to create that function here and let’s give it the return type of int and I’m going to call it get min like this and what I will need to pass to this function is going to be array so this array here so I’m going to say int numbers array so this is going to be the first argument and then the second one is going to be the size of this array so I’m going to say in size and we will use this second parameter here so that we know how many iterations we have to make in order to go through all of the elements of this array so let’s define this function the first thing that I want to do is I want to create a variable of type int and that variable is going to be called min so this is going to be the variable that is going to hold the minimal value so the smallest number in this array and initially I want to assign to this variable the first element of this array so I’m going to say that the smallest element initially is going to be the first one so I’m going to say numbers of zero and then we are going to iterate through all of the other elements and each time that we find an element that is smaller than the current value of our min we are going to store that value in our Min so let’s do that so I’m going to say four and since we have already stored the value of our first element in our Min we do not need to iterate through that so I’m going to say that my int initially has the value of one okay oh int I is equal to one like this and then our for Loop is going to iterate while our I is less than the size of this array so in this particular situation while our I is less than five and in each iteration we want to increment our I like this so as I already said if we find a number on a specific position which is in this current situation uh the position with the index of I if we determine that that number is smaller than our Min number like this we are going to store that number in our Min variable so I’m going to say Min is equal to numbers of I so that at the end of this for Loop in our Min variable is going to be the smallest number of this array so at the end of this for Loop here we can return our Min like this okay so now in order to test this function here I’m going to invoke it let’s say get actually I’m going to write it out I’m going to say C out Min is like this and then let’s invoke it let’s say get min like this and this get min function receives array so let’s pass it numbers array and then it receives the size of this array and this array has 1 2 3 4 five elements and you can check that here as well so we are going to pass Five here okay and if I run this program as you can see it says Min is minus 2 which really is the smallest number in our array so that is going to be the first function and then the second function that I want to create is going to be the one that is going to return the largest number in our array so let’s copy this function I’m going to copy it and then just modify it a little bit so the name of that other function is going to be get Max like this and then that function as well will receive numbers array and the size but here we are going to have variable which is called Max instead of Min and again we will assign it the value of our first element so then we iterate through all of these elements so starting with the second element because first the value of the first one we already have inside this variable so we do not need to check that but if we find in these remaining elements if we find element that is larger so bigger than our Max let’s copy this here we are going to store the value of that element in our Max variable like this and then at the end we will return our Max variable okay so now in order to test this function I will invoke it as we did with this previous one I’m I will just say Max is and then invoke get Max like this and I’m going to add two end lines here so that we have output which is formatted nicely and if I run my program now as you can see it says Min is minus 2 and then Max is 29 which is correct so let’s explain one more time the algorithm that we are using here in order to determine the biggest number of our array so here in this first line I say that the biggest number is the one with the index zero so the first one and then here we iterate through all of the remaining elements and that is from the one with index one until the last one and if we find that any of those remaining numbers is greater than our Max number then we say that our Max number is equal to that number so at the end of this for Loop we will have in our Max variable the largest number of this array here okay and we have accomplished to get our Min number and then our Max number using these two functions oh I’m sorry so using this get min and then get Max function as well so now what I want to show you is how you can use one function only to get both Min and Max number so let’s do that let’s create a function which we will name void get min and Max like this and this function is going to receive like these two previous functions our numbers array and the size of the array and then considering that we want to return two values from our function we will have to pass those two values by a reference which means we will have to pass the addresses of the two values and then this function here is going to change the value that is stored on those two addresses and this function here our main function is going to have the access to those two addresses as well so once this function here assigns the value of Min and Max numbers to those two addresses our main function is going to be able to access those values so as I said let’s pass to this function as well int Min like this and then int Max so we are receiving here pointer to A Min number and then pointer to a Max number okay so the job of this function will be very similar to the jobs of the two functions that we just created so I will just copy this and then paste it here and once more we are iterating through all of the numbers of our numbers array and then here we say if you find any number which is greater than our Max number and here we have an error which says operand types are incompatible so int and int pointer which means that here we have to D reference this pointer using the star symbol so if you find any number which is greater than our current Max please store that number inside our Max like this and then I’m going to copy this code one more time for our M number so I will say if you find any number which is smaller than our Min number like this Please assign that number to my Min number like this so this is going to be the work that this function will do and considering that this function is receiving these two so Min and Max as pointers this means that this function is directly going to modify the values that are stored on these addresses and those same addresses are going to be available in our main function which means that once this function changes the value vales that are stored on our Max and our Min address this main function here will be able to access those changed values and using pointers in that way we have achieved to return multiple values from our function so let’s invoke this get min and Max in order to test what I just said so I’m going to comment these two lines of code because we do not need them anymore and because here we have to pass Min and Max we will have to create those two variables here as well so I will say int Min and as we did before I’m going to assign to this Min the value of my first element like this okay and then I will create Max variable as well and assign to my Max variable value of my first element as well and now let’s invoke this get min and Max function so let’s say get min and Max and let’s pass it parameters that it needs so the first one is numbers array so I will say numbers and then second parameter is size of that array so five and then it expects to receive two pointers so Min and Max and we will have to pass addresses of our Min and then address of our Max as well like this and this here is called passing a parameter using a reference so that means pass an address of a variable to your function rather than passing variable itself because then if you don’t pass an address your function is going to create a copy and whatever changes your function makes with that copy you will not be able to see those changes in your main function so in this way we are passing addresses which means that this function here is operating on the original addresses which this function here is accessing as well so when this function here changes the values that are stored on those addresses this function here will know so that means that now if I try to write out oh I will need to add semic colum here at the end okay so that means now if we try to write out our Min like this Min is and then Min and then if we try to write out our Max as well Max we will get um values of Min -2 and 29 at least we expect to get those two values if this function is working correctly so if I run my program as you can see we really have values of min-2 let me just um collapse this so we really have values of Min -2 and 29 as the smallest and largest number in our array and we have achieved that using this pass by a reference so by passing addresses of our variables to our function which our function then changes the values that are stored on those addresses and since this main function as well has the access to those same addresses that means that our main function can see the changes that have been made on those addresses so I hope that now you have an idea how to return multiple values from a function using pointers so if you enjoyed this video If you learned something new give it a thumbs up and also subscribe to my channel and I will be publishing more videos related to pointers in the future so if you don’t want to miss out on those press Bell icon as well thank you for watching and I’m going to see you in my next video bye hi everyone welcome to my channel my name is Salina and I make it and programming related videos so if that is something that is of interest to you consider subscribing to my channel and give this video a thumbs up as well and in this video I want to talk about Dynamic arrays so you should already be familiar with the idea of arrays and the concept of fixed arrays from my previous videos but for those of you that really want to understand the need for dynamic arrays I will go through some of the advantages and disadvantages of fixed arrays so that you can really understand where the need for dynamic arrays arised so we said that an array is type of collection which stores elements in continuous memory now that means that it stores elements one after the other so if I do this for example if I say let’s create an integer array of five elements and let’s call that array my array like this your computer in the background will do the following it will give to this array here five containers of type int and those containers will be one after the other in memory so that means because the array stores data in a continuous memory so one after the other accessing that data will be very very fast so because the name of the array is the address of the first element of that array when you specify the name of the array and then you give it the index of the element that you want to access it is going to be very fast to move from that first element until that position that you specified so until the element that has that index whereas if you use some other collection type like linked list for example which stores data in non-continuous memory which means in a random places in memory and then each element contains a pointer to the previous one and to the next one accessing elements in those type of collections would be much slower so if you wanted to access Fifth Element of linked list you would have to Traverse the first four elements and then get to the fifth one because they are stored in noncontinuous memory meaning they are randomly in your memory so as I already said accessing elements of an array is a very very fast operation but because your array stores data in continuous memory this has certain disadvantages as well so what happens if you want to insert or delete an element in the middle of the array for example so how can you insert or delete an element in the middle of the array without breaking that continuousness if I can say it like that so you get the point that means that the operation of inserting and deleting elements in an array is going to be much slower than inserting elements in a linked list for example and if you want me to do a video which is related to differences between linked lists and arrays for example write it in the comments down below and I will make it in the future when I find time so again if you are not familiar with the basics of arrays I recommend you to watch my first video which is related to arrays and pointers which I will link here and then you come back to this one so those were some advantages and disadvantages of arrays and it will be up to you to decide which collection you want to use however here I want to give you the biggest disadvantage or the biggest obstacle that we encountered so far when working with arrays and that is the following so the size of the array had to be constant which means that the size size of the array had to be known before we even started our program so we always kind of wanted to do this so we wanted to say int size and then we wanted to ask our user to enter the size so please enter the size for the array and then after our user enters the size for the array we wanted to create the array that is of that size that our user specified however we get the error as you can see here it says expression must have a constant value which confirms what I just said which is that the size of the array had to be known at compile time so the size of the array could not be changed once we declar it it and we had to declare it before we even started our program so this problem was without solution so far but surprise surprise if you know how to work with Dynamic arrays and dynamic memory you can very easily create an array and runtime so in C++ there are two keywords or two commands which allow you to allocate and deallocate dynamic memory which means to get yourself dynamic memory when you need it and then free that memory once you don’t so that it can be reused that is what allocate and deallocate means and those two commands are new and delete so new allocates memory as you may guess and then delete deallocates that memory or freeze it once you don’t need it so let’s see how we can use this information that I just gave you on our example so instead of doing this here I will comment it because we do not need it instead of doing this what I will do is I will create a pointer like this and let’s call that pointer my array and what I want to assign to this pointer will be the following I will say please make this pointer point to new integer array and the size of that array will be this size that our user entered like this okay and as you can see our compiler is fine with this expression here we do not have an error so this new keyword has allocated an array of this size that our user has specified and that array aray the address of the first element of that array is stored in this my array pointer so if I build this code as you can see we do not have compile time errors so what I want to show you now is how we can enter elements for this array and then how we can write them out and this is array again this is array which is created at runtime so our user will specify the size of this array which is something that we were not able to do before we learned how to use Dynamic arrays so uh in order to enter elements for this array here as we already know we will be using four Loops so I will say four please iterate from the element which has index zero until you come to the element that has the index of this size okay and then in each iteration increase our count counter by one and what I want to do is I want to write out a message for my user so I will say array and then let’s add index of the current element index that our user is entering so I like this okay and then what I want to do is I just want to enter an element on that position that we are current Curr it rating so I will say my array of I like this so using this code here we should be able to enter elements in this array here and then in order to write these elements out what I will do is I will use another for Loop so I will just copy this one and then paste it here and in this particular situation I just want to write out so I will use C out command and and then these other red Direction signs so I just want to write out all the elements of the array and I will add a few empty spaces after each element so that we have a nicely formatted output so this Loop here should write out the elements of our array and if I start this program now as you can see it asks us to enter the size of the array so let’s say five for example and now we are we are entering ele with index zero so let’s say 2 5 7 9 and let’s say 11 okay and as you can see here we have the elements of our array written out and we wouldn’t be able to do this if we didn’t know how to work with Dynamic arrays so let’s stop this program and there is one more thing that I want to mention and that is following these square brackets here are only one way to dreference your array another way to dreference the array or to to access the element on a specific position is the following so so the other way to access the element on a specific position would be using this asteris symbol and then here you say my array plus I now because the name of the array is the address of the first element here you have the address of the first element and then when you add a certain number to that it will move that many spaces in memory and then access the element on that position and when you dreference that you will get the value of that element instead of its address so here is one way to dreference your array and then here is another way to dreference your array and you can use whichever one you prefer and if I run this program again just to demonstrate that it works the same let’s say three and then one 5 10 okay we get 15 10 as the elements of our array one very important thing that I mentioned at the beginning is that we have two commands for working with dynamic memory and one of those two commands is new so we said that new is a command which will allocate memory for us when we need it and then another one is going to be delete and delete is a command which will de allocate that memory when we do not need it so that it can be reused Now using dynamic memory comes with a responsibility and that responsibility is the following each time that you allocate memory when you need it you will have to deallocate that memory once you don’t so that that memory can be reused so that means that each time that you write new command you will have to write delete command once you don’t need that memory anymore so I will demonstrate how can you deallocate the memory that we have allocated for this my array so let’s say that here in this line of code we do not need our array anymore so how can I deallocate the memory that I allocated for this array well using delete keyword and I will say please delete the memory that I allocated for my array which is called my AR array like this and you have to specify these square brackets because that is the way that you allocated memory so here you said I want new array and then here you have to say please delete that array and a good practice is to do the following as well so you can say my array is equal to null like this and let me collapse this so this here is going to assign the value of null to your array so your array will not point to anything to any address at this line of code so why do we do this because in the previous line of code we have deallocated this array here and now in this line of code here your array will point to a location in memory which does not belong to you so it does not belong to your program and because of that because we do not want to cause some accidental crashes or problems in our program by having this array pointing to memory locations which are not ours anymore it is a good practice to say that our array is now equal to null which means that it is not pointing to anything so as I already said and I repeat again when you use dynamic memory each time that you write new you will have to write the lead that corresponds to that new so here I have allocated an array and here I am deallocating that array so I hope that this video was helpful and that this video helped you understand what are Dynamic arrays and how they work and now that I have explained this it opened the whole world of new possibilities and new things that you can do with Dynamic arrays and I will leave to you to play and discover those new things until my next video of course so thank you for watching this video give it a thumbs up if you liked it subscribe to my channel click the Bell icon as well and I’m going to see you in my next video bye hi everyone welcome to my channel my name is Alina and I make it and programming related videos so if you’re interested in those please subscribe to my channel and give this video a thumbs up and in this video I want to talk about a topic that confuses many students and that is the topic of multi-dimensional dynamic arrays and the topics like this one are the reason why many people step away from learning C+ Plus+ and they believe that learning C++ is hard but what I think is that many of those people never actually had the opportunity to have this explained in a very simple way so that is what I will try to do in this video so with the help of excel I will try to draw what are multi-dimensional Dynamic arrays and how they work and I hope that at the end of this video you will have it pretty clear and you will be able to create and work with your own multi-dimension Dynamic arrays so what a multi-dimensional array is in simple words it is array of arrays and in this video you will learn how to create two dimensional Dynamic arrays and in order to be able to understand this topic you should be familiar with the topic of dynamic arrays which is a video that I already did on my channel and I will link it here so make sure to watch that video before watching this one so I will very quickly remind us all of how Dynamic arrays work and then we will see how we can use that knowledge to understand multi-dimensional Dynamic arrays so let’s create a visual representation of a dynamic array in our Excel sheet so let’s say that it will be array of four elements like this this is our array and the indexes of these elements start with zero and then 1 2 3 so these are the indexes and then the address of this first element will be for example 000000 AA like this and this address here it is the address of the first element but it is the address of the array itself as well and you should be familiar with that so this here is our dynamic memory and then on our stack which will be here let’s create our stack so this here will be our static memory here we will have to create a pointer variable which will hold the address to this element here or actually the address to the array itself so I will create a variable let’s call it PTR 1 so this is going going to be our pointer one and as we already said that pointer will hold the address of the first element of this array let’s copy that address like this and then we will store that address in our PTR 1 now if we wanted to create more array way by the knowledge that we have so far we would have to copy this and then let’s paste it here and let’s create one more array like this so now we have three Dynamic arrays and the first element of the first array has the address of 0 0000 AA and then this one here let’s say that it has the address of BB for example and then this one here has the address of 0000 CC and to be able to access these arrays we would have to create on our stack two more pointers so let’s do that okay so our pointer 2 will hold the address of the second array which is 0000 BB and then our pointer Tre would hold the address of our third array which is 0000 CC like this now with this we have created three Dynamic arrays and in order to create those three Dynamic arrays we had to create three pointers so those are these three here and this is something that you should already be familiar with so you should already know from my previous video how to create a dynamic array now one thing that I see here and that is a problem is that if we wanted to create four or five or 100 of these Dynamic arrays we would have to create that number of pointers on our stack which means that this part here is not Dynamic only this part here is dynamic because here our user determines how many elements this Dynamic array will have but for each of these Dynamic arrays we have to manually create a pointer on our stack which will hold the address of that array okay now what happens if I want to move this part here to our dynamic memory as well so let’s do that let me cut it from here and then I will paste it here for example so now I have moved this part to dynamic memory as well and as you can see here this kind of looks like an array as well so that means that this first element if we look at this as an array the first element will have index of zero and then second will have index of one and then third will have oh this won’t move third will have index of two okay so this is an array that has three elements and the first element for example has the address of 00 0 e e e e like this so now this part here is dynamic and then this part here is dynamic and in order to be able to access this array here what we have to do is on our stack which is this part here we will have to create a pointer which will hold the address of this first element so let’s do that let me just okay now as I already said on our stack we will have to create a pointer which will hold the address of this first element so let’s call that pointer table for example and this table will hold the address of this element here which is 0 0 e e e e and this table because it holds the address it should be a pointer but one thing to keep in mind is that this variable here is not a simple variable but this here is a pointer as well which means that this table will not be a simple pointer but it will be a pointer to a pointer and you indicate that using two ASX symbols because one is just a pointer and then two mean a pointer to a pointer why because this table holds the address of the element which is this one here and that element is pointer as well okay now if we look at this here as you can see we have one array that represents the number of rows that our table will have okay so one 2 3 and then for each one of the elements of this array here we create a separate Dynamic array like this so this here will be our table that has the number of rows that are user defines and then however many columns are user defines as well and in this particular situation it is a table that has three rows so these are three rows and then four columns so let’s now translate this to our C++ code and because we said that now our user defines how many rows this table will have and then how many columns as well that is the first thing that I will do so I will create two variables let’s call them int rows and columns and then I will ask my user to enter how many rows and how many columns he wants this table to have so let’s do that see in rows o and then columns like this okay now after our user has entered how many rows and columns he wants what I want to do now is this part here so this part here this is our first step and then this here is going to be our second step and this part here will be the third step so this part here will be the following when translated to C++ code so here as I already said I create a pointer to a pointer which I will call table so I will say please create an integer pointer to a pointer because here we will store integer values you can create a character or double or float whichever one you want I want to create integer pointer to a pointer and call that table like this okay so we are done with this first part here and then what this table pointer to a pointer will point to is going to be this array here so I will say please create a new in integer array that has this many elements so the number that our user has entered for this rows variable because this rows variable holds how many elements this array here will have but as you can see here we have an error and that error is happening because this here which is this array here is not just a simple integer array but it is array of pointers so here you will have to indicate that so you will have to say please create an integer array of pointers and as you can see now our error has disappeared and with this line of code here we have created this array here now our third step is going to be that for each element of this array here we would have to create a separate Dynamic array so this first element will hold the address of this Dynamic array and then this second element holds the address of this array and then this third the address of this array here so what I will have to do is I will have to iterate through all the elements of this array and for each one I will have to create a separate Dynamic array so let’s do that so I will say for in I is equal to zero and then I is less than the number of rows that our user entered and in each iteration increment I so in this particular situation our number of rows is equal to three but you can have as many as you want so what I want to do in each of these iterations is I want to create for each one of these elements a separate Dynamic array so I will say table of I is equal to new integer array that has this many elements and that is the number that we stored in our columns variable like this and with this code here we have successfully created these Dynamic arrays now how do you access elements on a specific position of this table here for example this one or this one or this one so in order to do that let’s say for example table of Row one and then column 2 will have the value of 88 now what this could here what this line here will do is the following so this part here it says please give me the table variable which is this one here and it is a pointer to a pointer which holds this address here so 0 0 e e e e and that address is the address of this element here so the address of this array and here we say please give me the element of that array that has index one which is this element here so it is the element that stores the address of 0000 BB which is the address of this array here and this second part says please give me the element of that array that has the index of two which is this element here so here we will store the value of 88 so that is what this line of code here will do it will store number 88 to this position position here so this line of code here will store this number at the element that has row index one and column index two of this table so this here is a row with index zero this here is a row with index one and then two so we are storing at this row and then column index two is this one here so here we store number 88 one thing that we said as well in my previous video is that each time that you allocate dynamic memory you have the responsibility to deallocate that memory when you don’t need it which means each time that you use new keyword you will have to use delete keyword when you don’t need that memory anymore so now is the question how do we deallocate all of this memory that we have taken so in order to do that what I want to do is I want to show you something if for some reason we lose this address here so the value that is stored in this table pointer to a pointer we will never be able to access all of these elements that we have created in our dynamic memory so that means that we will not be deallocating this first and then if we for some reason lost this the value of our 000000 AA for example that means that we would never be able to access this array here so we would never be able to deallocate this memory so that means that this is not going to be deallocated it first as well now allocation of this memory here went as follows this was the first step so this was the first thing that we allocated and it is this code here and then we allocated this so that corresponds to this part here and then the last thing to allocate was these arrays here and that corresponds to this part of the code and the allocation of this memory will go the other way around which means that first we will deallocate this and then we will deallocate this and then this will be the last thing that we will have to worry about now in order to deallocate this the process will be almost the same as the one when we allocated it so I will copy this for Loop and then paste it here but what I want to do in this particular situation so when the allocating is instead of creating a new Dynamic array for each table of I is I want to delete that array so for each element of this array here I want to delete the corresponding Dynamic array so I want to delete these three arrays and in order to do that I will say please delete the array that my table of I is pointing to now what this code here will do is for this element here it will deallocate this array here so let’s delete that and then for this element here it will deallocate this array and then for this one it will deallocate this array here so now we have successfully freed this memory that we have taken here now after we have done this after we have successfully deallocated our first step which was here this part here will be our second thing to deallocate so here I will say please delete the array that my table variable is pointing to so this line of code here will deallocate this part here so I will say please delete that we do not need it anymore okay and then our third step which is the last one will be to null this value here why because we have just free the memory that was here so we have deallocated that now someone else might be using this memory here and we really shouldn’t keep the address of someone else’s memory so we should make this a null value like this and in order to do this in our code I will just say now my table will hold the value of null like this and this will prevent some potential crashes and problems in your application so I hope that this video helped you understand multi-dimensional Dynamic arrays a bit better and if it did please give it a thumbs up and subscribe to my channel because that helps me to reach more people and hopefully make programming a little bit easier for them as well thank you very much for watching and I’m going to see you in my next video bye hi everyone welcome to my channel my name is Alina I’m a software engineer and I make it and programming related videos here in YouTu YouTube and in this video I will be doing something that I haven’t done before and that is reviewing your code and we will see some errors that you guys have sent me so I get a lot of messages a lot of questions on my Instagram on Twitter and then here on YouTube as well in the comments where you ask me for an opinion or for advice on certain errors that happen to you in programming and I try to answer as many of those as possible but it’s just not possible to answer to all of you and I’m very very sorry but I thought that it would be a good idea to make a video related to that so that all of you can see it so here I am I’m making that video right now so in this video I will be reviewing some code and we will see some errors that can happen and that do happen very often and I’m going to do that both manually and then I want to show you a very cool tool which is called PVS Studio I’m going to leave details in the description down below so that you can check it out for yourself but what PVS studio is it is static code analyzer so it is basically a tool that reviews your code and helps you detect bugs and errors and security weaknesses in your code so in the case that you need another pair of eyes to look at your code and give you a few tips and recommendations it is a great tool to use and you can get it as a team license for teams up to nine people or you can get an Enterprise license for bigger companies bigger departments or you can even request a free license if you are a student if you are working on some private projects or on some open- Source projects and then one very cool thing is that it is not only used to analyze C++ code but you can use it for C and then C and Java as well uh and I wondering guys which team are you in are you team C++ or are you team C or Java or C um I’m very curious to read your answers so please write me in the comments down below and if you ask me I’m definitely team C++ and then team c those are just two of my favorite languages ever but I am very curious to read what you will answer to this question so um I’m going to leave all the details about PVS studio uh in the description of this video so that you can check it out for yourself and let’s jump into the coding part right now because I am very very excited to do this here I have created a new project and I have this program that does basically nothing so what I want want to do is I want to check if everything is okay with this code so far so if we have made any errors so far so I’m going to click on extensions and then PVS studio and here you have multiple options you can check your current file you can check open files or you can check your project selected items solution I’m going to select this first option so I’m going to check this current file and you get this window here and as you can see we have one error and that error is that my license will expire in 5 days okay so that is not error which is related to our code so we are just going to ignore it so we don’t have code errors so far and let me show you how you can install this tool very quickly so you click on extensions and then manage extensions okay and then here you can search for PVS Studio like this okay great it is this one here so PVS studio is a tool for detecting bugs and security weaknesses and so on okay so you will click download here and your download should begin I’m not going to do that right now because I already have it but once it is downloaded the installation is pretty simple so it’s basically next next next finish installation so that should be simple okay now let’s close this window here and as you could see we don’t have any errors with this code so far so let’s write some code and let’s create some errors now so so let’s create an array of type int and I will call it saved money and that will be array of five elements and I want to initialize those elements here so the purpose of this array is following let’s say that I want to save some money each month and I want to store that data in this array here so I’m going to save money for five months and I will store how much money I have saved each month inside this array here so for example the first month I have saved $100 or Euros or whatever and then second month I have saved 200 and then 300 and 400 and 500 fifth month okay so this is our array now what I want to do with this data here is I want to Summit after 5 months I want to know how much money I have saved in total so I’m going to create a variable of type int and I will call it total like this and I will initially give give it a value of zero and then I will iterate through this array here so I will say for INT I is equal to zero and then I is less than or equal to 5 and then I ++ and what I will do inside this for Loop is I will say that my total will hold whatever my total was previously holding plus current value of how much money I have saved in that month so saved money off I okay now after I have done this I will just write out how much money I have in total so I will say total and then this value that is stored inside this variable here okay now if I run this program let’s see what will happen well it says that in total I have minus 8 billion something very very big number so I have tried to save each month and then at the end I have minus8 billion dollar you know so that does not make any sense so here we have a logical error okay so let’s see what is this error that is happening so let’s click on extensions and PVS Studio check current file to see what kind of error PVS Studio sees and it says array over run is possible the value of I index could reach five and if I double click on that it will take me here and this part of code here is underlined and this is actually our compiler our compiler is underlying this and it says that okay it says index 5 is out of valid index range of 0 to four so this here this situation here says that this I is out of range of valid indexes that this array here can have and if you are familiar with arrays you know that indexing of an array starts zero so the first element has index of zero and then 1 2 3 and four so valid indexes for this array here are from 0o to four and here we have accidentally written that this I is less than or equal to five and that is making a problem so if I delete this part here so if I say that my I is just less than five this error should disappear so if I click on PVS 2 studio and then check current file the error should disappear okay it has disappeared now so if I run my program this program is behaving as expected so this is one thing that very often happens you can accidentally write less than or equal to and then you can get a very very big logical error another thing that can happen is if you’re typing very quickly and if you lose concentration for a moment and and here instead of incrementing you decrement this counter so you say I minus minus you should get an error as well so if I try to build this program let’s see what our compiler will tell us so here in this error list it says ill defined for Loop counts down from minimum so that’s kind of helpful um information and then another let’s read this other warning it says reading invalid data from Saved memory the readable size is 20 bytes but minus 4 bytes maybe read so this is not really help helpful for someone who’s just starting and then this third message it says index minus 2 billion something is out of valid index range 0 to 4 again this is not really helpful for someone who is just starting so uh let’s see what our PVS Studio has to say so I’m going to click extensions PVS Studio check current file okay and this first error here here says the condition I less than 5 of for Loop is always true so this is actually a helpful message and if I click on this I will be taken here and it says that this condition here I is less than five is always true but why is it always true because we have started counting at zero and then we try to decrement that value in each iteration and uh doing that we can never reach this condition here this condition here will never become false so that means that here we have created an infinite Loop and here our PVS Studio says consider inspecting this for operators so consider inspecting this for Loop here because it will not be executed at all or it can be executed incorrectly and in this particular situation it is going to be executed incorrectly so it is going to be an infinite Loop which we don’t want in this particular situation so I’m going to correct this error here so I’m going to return it to i++ but that is sort of a help that you can get from PVS studio and this here is a pretty simple program because it has just a few lines of code where all the bugs can potentially happen but imagine working on a very very big project and then something like this happens so imagine something like this happening uh on a program that a bank uses so you are trying to save money for a couple of months and then the program says that you are in depth that your balance is minus 2,000 or 20,000 or something like this so this can create very very big issues and in this particular situation if you have a bug like this you will want to have all the help that you can get and sometimes that can be uh just the help that you get from your compiler or if you have a very very big problem you will definitely benefit from tools like PVS Studio which will give you some additional information on that situation that is happening and on that problem that you you are having and then there are other situations where you can have very very big problems but your compiler will not be helpful at all because your compiler will not be able to see those potential bugs that you are creating inside your code so in order to demonstrate that let’s delete all of this code here because I will not need it anymore and what I do need is to create a function here so let’s create a function of return type void and I’m going to call it my function like this okay and what I want to do inside this function is I want to create an integer pointer PTR so if you’re not familiar with the topic of pointers make sure to watch the playlist that I will link here it is the playlist where I explain pointers in C++ because it is one of the most important topics in C++ and it is the example that I will be using here so I have created an integer pointer and I’m going to say now you will point to a new array of integers and that array will have five elements like this now what do I want to do with this array well let’s do something very simple let’s say PTR of two will hold the value okay it will hold the value of 10 like this and then let’s just write out something let’s say hi I am equal to and then PTR of two okay so this here is pretty simple example that does basically nothing important nothing useful but I will use it to demonstrate a very very big issue that can happen in this situation so I’m going to invoke this function here so I’m going to say my function like this and I have successfully invoked this function so if I run this program it says hi I am 10 so nothing unexpected happened or did it okay um if I inspect my errors list it says that I don’t have any errors so if you ask a compiler it will tell you that everything is perfectly fine so let’s now ask PVS Studio here it has already detected two potential issues but you can click PVS studio and then check current file just to be sure okay and it says visibility scope of the PTR pointer was exited without releasing the memory a memory leak is possible so what we have done here in this program is we have created memory leak where here so here we have said please give me in my dynamic memory give me array of five integers and this is going to be done in dynamic memory so once this function is finished once this function ends we are going to lose this PTR so we are going to lose the address of the first element of this array here so here if I try to do something like PTR I cannot access this variable here anymore this variable has its scope and that scope is inside this function here and once this function exits we are going to lose the address of this array here which means that we will not be able to deallocate this memory here now let’s delete this okay here as you can see this memory leak is not a big memory leak here we are leaking five integers so we are leaking an array of five integers and that is not very big problem but usually what happens in real life is that you are not creating an array of five integers usually you are creating things that require much more memory than just an integer array of five elements so here as I said we are leaking five integers but imagine a situation where you are creating an array of 5,000 or 50,000 and not integers but objects of type user like this and this user has some pretty heavy data in it for example it has some images and things like that so here you are creating 50,000 users and to make things worse imagine not invoking this function only once but imagine invoking this function in a for Loop for example so invoking it 100 times or 1,000 times or 100,000 times that is going to be a huge memory leak so what this line of code here does is it asks your operating system for dynamic memory so it says please can you give me new memory so can you give me dynamic memory that I need to store this data here and your operating system gives that memory to your program so it allocates that memory for your program and then once this function here finishes you will lose all the variables that you have created inside that function and that is this PTR variable here so that means that the address of this array here which was stored inside this PTR variable is lost now and now you will not be able to deallocate this memory here which means that you will not be able to say okay now I am done with this memory which is a lot of memory and now I’m going to return that back to my operating system because I don’t have unlimited amounts of memory and my operating system maybe would like to give that memory to some other program so once this function here ends and you don’t deallocate this memory here you are leaking that memory and that is exactly the error that you have here it says a memory leak is possible whereas your compiler here said expected a type specifier which is U error that we have here because it does not know what is this user so I’m going to return this back to int okay now that error has disappeared but your compiler does not know that you are leaking memory here whereas your PVS Studio analyzer here says that a memory leak is happening so how do you fix this error here well for each new you need to have delete again you need to watch my C++ pointers playlist in order to understand pointers if you don’t understand this already so as I said for each new you need to have delete so I’m going to say delete and let’s delete this PTR let’s see what is going to happen now so if I click extensions and then PVS Studio check current file it says the memory was allocated using new array type operator but it was released using delete operator and then it gives you a recommendation here it says use delete array pointer it set instead so here we are trying to allocate memory for an array but we are not deleting that entire array so here we are leaking memory again so here I’m going to use these square brackets in order to indicate that I want to delete this entire array that I have allocated in this line of code here so now we shouldn’t be leaking memory anymore so let’s check that out I’m going to say PVS Studio check current file and let’s see we have that error that we previously had which is your license will expire in 5 days but we do not have memory leaks anymore which is great so errors like this memory leaks are very common when you work with pointers in C++ and these memory leaks can create huge problems if you have them in your code and as you could already see in most cases you cannot really on your compiler to tell you that you are leaking memory because in most cases it will not even be able to see that so tools like PVS Studio can be very helpful in those situations you could see all those little tips and recommendations that we had from PVS Studio that helped us to fix issues that we had related to leaking memory so those were some topics that I wanted to address in this video because many people when working with pointers will come across problems that they will not be able to fix or they will not even be aware that they have those problems that they have memory leaks until it gets to the point where it is unmanageable and they have very big problem they have huge problem so um if you have any more questions that you would like me to make video on please leave those in the comments down below and if you like this type of video please give this video a thumbs up so that I can know and I will make more videos like this in the future if you want me to so thank you very much for watching this video and I am going to see you in my next video bye hi everyone [Music] well okay so hi everyone welcome to my channel welcome to another [Music] [Applause] [Music] hi everyone Hi everyone welcome to Welcome to my channel so this here is the initialization step of our initialization initialization in initialization initialization so it is the in in

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

  • C Programming: Library Creation, Encryption, and System Call Hijacking

    C Programming: Library Creation, Encryption, and System Call Hijacking

    The provided texts encompass diverse topics in programming and computer science. One excerpt focuses on creating a SOCKS version 4 client in C to connect to the Tor network, detailing packet creation, data transmission/reception, and proxy traversal. Another segment explores XOR encryption, demonstrating its implementation in C for single-character encryption/decryption. A further discussion involves creating an encryption library using a modified ARC4 algorithm. An additional piece elucidates Linux file system permissions, explaining read, write, and execute permissions alongside their numeric representations. Finally, a text introduces creating a safe string library in C to avoid buffer overflows and memory corruption issues when handling strings, and the last text describes the use of functions to hijack connections made through the tour network by creating shared libraries and altering prioritization order.

    Source Code Deep Dive: Study Guide

    I. Quiz

    Answer each question in 2-3 sentences.

    1. What is the difference between a system call and a library call, and how can you determine which one is being used?
    2. What is the purpose of the htons() function, and why is it needed when working with network addresses?
    3. Explain the role of a makefile and the benefits of using one when compiling C code.
    4. What are the three essential elements needed to establish a TCP connection, and what specific steps are involved in configuring these elements?
    5. Explain the concept of a “predicate” in programming.
    6. How does the XOR operation work, and why is it useful for basic encryption?
    7. Why is it important to zero out buffers in the example code provided?
    8. What is a “type definition” in C programming, and what is its purpose?
    9. Explain the purpose of the assert() function and how it can be used for debugging.
    10. Explain what LD_PRELOAD does and how it can be used to override existing function calls.

    II. Quiz Answer Key

    1. A system call is a direct request to the operating system kernel, while a library call is a function provided by a library that may eventually use system calls. To determine which one is being used, you can consult the manual pages using man 2 for system calls and man 3 for library calls.
    2. The htons() function converts a host’s byte order to network byte order. This is necessary because different systems use different byte orders, and network communication requires a consistent order.
    3. A makefile automates the build process by defining dependencies and commands for compiling and linking code. This simplifies the compilation process, especially for projects with multiple source files.
    4. The three essential elements are the address family, the port number, and the IP address. These elements must be configured in a socket address structure before initializing the connection with the connect() command.
    5. A predicate is a function or operation that returns a boolean value, indicating whether a certain condition is true or false.
    6. XOR (exclusive OR) is a bitwise operation that returns 1 if the input bits are different and 0 if they are the same. It’s used for simple encryption because applying the same key twice decrypts the data.
    7. Zeroing out buffers ensures that they are initialized with a known state, preventing potential issues with leftover data or undefined behavior.
    8. A type definition creates an alias for an existing data type, making the code more readable and easier to maintain.
    9. The assert() function checks if a given condition is true, and if it’s false, the program terminates with an error message. It’s used to catch programming errors and ensure code integrity.
    10. LD_PRELOAD is an environment variable that specifies shared libraries to load before any others. It can be used to intercept and replace function calls, effectively overriding existing system behavior.

    III. Essay Questions

    1. Discuss the security implications of using a simple XOR encryption method, and explain the limitations of its cryptographic strength.
    2. Analyze the structure of a SOCKS version 4 client and its role in connecting to the Tor network.
    3. Elaborate on the benefits and drawbacks of using the getrandom() system call for generating cryptographically secure random numbers.
    4. Explain the purpose of “whitewashing” the RC4 keystream, and how it enhances the security of RC4 encryption.
    5. Explain the advantages and disadvantages of manually managing strings compared to using standard C functions, highlighting the security implications of both approaches.

    IV. Glossary of Key Terms

    • System Call: A request made by a program to the operating system kernel to perform a specific task.
    • Library Call: A function provided by a library that may eventually use system calls.
    • Socket: An endpoint of a two-way communication link between two programs running on the network.
    • TCP (Transmission Control Protocol): A connection-oriented protocol that provides reliable, ordered, and error-checked delivery of data between applications.
    • SOCKS (Socket Secure): An Internet protocol that routes network packets between a client and server through a proxy server.
    • Tor (The Onion Router): A free and open-source software for enabling anonymous communication.
    • Proxy Server: A server that acts as an intermediary between a client seeking resources and a server providing those resources.
    • Makefile: A file containing a set of directives used by the make utility to automate the compilation and linking of software.
    • Byte Order (Endianness): The order in which bytes of a multi-byte data type are stored in memory.
    • Network Byte Order: A standardized byte order used for network communication, typically big-endian.
    • Host Byte Order: The byte order used by the host system, which may be big-endian or little-endian.
    • htons(): A function that converts a 16-bit host byte order to network byte order.
    • AF_INET (Address Family Internet): An address family that is used to designate the type of addresses that the socket can communicate with (IPv4).
    • SOCK_STREAM: A socket type that provides sequenced, reliable, two-way, connection-based byte streams.
    • Predicate: A function or operation that returns a boolean value (true or false).
    • XOR (Exclusive OR): A bitwise operation that returns 1 if the input bits are different and 0 if they are the same.
    • Ciphertext: Encrypted data.
    • Cleartext: Unencrypted data.
    • Type Definition: A statement that creates an alias for an existing data type.
    • Assert(): A macro that tests a given condition, and if the condition is false, the program terminates.
    • Maloc(): A function that allocates a block of memory dynamically.
    • LD_PRELOAD: An environment variable that specifies shared libraries to load before any others.
    • RC4 (Rivest Cipher 4): A stream cipher widely used in software applications and protocols.
    • Keystream: A sequence of pseudo-random bytes used to encrypt or decrypt data.
    • Whitewashing: The process of discarding initial keystream bytes in RC4 to mitigate certain statistical weaknesses.
    • Entropy: A measure of the randomness or unpredictability of data.
    • getrandom(): A system call that retrieves random bytes from the kernel’s entropy pool.
    • DL_SIM: A flag in some C compilers, like GCC, that is used to link a dynamically loaded library, and tells the linker that all symbols in the library should be considered defined, even if they are not explicitly used.
    • LD_PRELOAD: An environment variable used to specify shared libraries that should be loaded before others.
    • Change Mod: (chmod) the command for altering permissions on a Unix and Linux system.
    • Change Own (chown) the command which changes the owner of a specific file in Unix and Linux system.

    Tor Tunneling Tool: Development and Security Briefing

    Okay, here’s a detailed briefing document summarizing the key themes and ideas from the provided source material.

    Briefing Document: Tor Proxy Tool Development & Related Concepts

    Overview:

    The sources document the development process of a tool (“talize”) designed to tunnel network connections through the Tor network. The materials also touch on foundational concepts related to networking (system calls, library calls, TCP connections), security (encryption with XOR, file permissions in Linux), and C programming (dynamic linking, shared libraries, memory management).

    Main Themes & Important Ideas:

    1. System Call Interception for Tor Tunneling:
    • The core idea is to intercept system calls (specifically, connect) made by other applications and redirect the connections through a Tor proxy. This allows any application to utilize the Tor network without explicit configuration within the application itself.
    • The tool uses LD_PRELOAD to inject a shared library that overrides the standard connect function.
    • “You remember I want to be able to do something like talize and then run any [Music] command like curve against some IP address and then I want to in intercept the connection I want to run this command as is but I want to intercept the con the connection that the actual program does and run my code instead so it tunnels through the tour Network any program that we want to run…”
    1. SOCKS4 Proxy Implementation:
    • The tool establishes a TCP connection to a SOCKS4 proxy server (typically running on localhost at port 9050 when using Tor).
    • The source code shows the creation of a socket, setting the socket address family to AF_INET, specifying the proxy port, and using the connect system call to connect to the proxy.
    • “So now we have successfully created our TCP connection towards the proxy server and the next step is to create the uh proxy request packet according to this structure that we created before.”
    • The source code shows the creation of a socket using socket(SOCK_INET, SOCK_STREAM, 0).
    1. C Programming Techniques & Challenges:
    • The source code demonstrates various C programming techniques, including:
    • System calls (e.g., socket, connect, close, open, read, write, getrandom).
    • Library calls (e.g., htons, inet_addr, strlen, malloc, free, perror, sprintf, snprintf, memset).
    • Pointers, structures, type definitions (typedef).
    • Dynamic memory allocation (malloc, free).
    • String manipulation.
    • Function pointers (for intercepting system calls).
    • Shared libraries (.so files).
    • Bitwise operations.
    • Challenges encountered during development include:
    • Compiler errors and warnings (due to type mismatches, incorrect syntax, missing include files, etc.).
    • Memory management issues (leaks, segmentation faults).
    • Debugging dynamic linking issues.
    • Getting terminal settings correct for password input (disabling echo).
    • Troubleshooting network connectivity problems.
    1. Security Considerations:
    • The material briefly mentions the importance of using cryptographically secure random number generators (getrandom) for security-sensitive tasks.
    • The use of XOR encryption is described as a simple demonstration and not suitable for real-world security.
    • The need to “whitewash” the initial state of RC4 is also mentioned to mitigate potential weaknesses.
    • File permissions and ownership within a Linux environment were mentioned.
    • “This is a very basic form of encryption that uh is only for demonstrational purposes it’s quite easy to crack with today’s Technologies and computer power however it’s a good example on how to use exor…”
    1. Dynamic Linking and LD_PRELOAD:
    • The tool relies heavily on dynamic linking, using LD_PRELOAD to inject a custom shared library that overrides the standard connect system call. This allows the tool to transparently intercept and redirect connections made by other applications.
    • The source contains instructions on setting the LD_PRELOAD environment variable.
    • “So we need to send everything that’s on the right of this toriz and there is a way to access all the arguments at the same time and I I think it is done like this okay so first we export the LD preload and point it towards our shared library then we do the dollar and I think it’s the at sign which will run all the arguments to this uh script…”
    1. Practical Implementation of RC4 Encryption:
    • A significant portion of the material details the implementation of the RC4 encryption algorithm.
    • The code includes functions for:
    • Initialization (Arc4Init).
    • Key stream generation (Arc4Byte).
    • Encryption/Decryption (Arc4Encrypt).
    1. Safe String Handling:
    • The need for safe string handling is emphasized to prevent buffer overflows and other security vulnerabilities.
    • The material describes a custom string library that provides functions for:
    • Initialization.
    • Concatenation (automatically reallocating memory as needed).
    • The source shows implementations of custom length and copy functions for increased control over string manipulation.
    1. File Permissions in Linux:
    • The sources include an explanation of file permissions in Linux using chmod.
    • This includes the meaning of the numeric representation (e.g., 755) and its relationship to read, write, and execute permissions for the owner, group, and others.
    • “What does this 755 mean in the detail this and more we’re going to talk about today when we are discussing Linux file system [Music] security…”

    Quotes from Original Sources:

    • “is a system call that’s why how do you know if it’s a system call or a library call try a library call first three if you don’t get a hit or if you get a hit that doesn’t seem right try the uh the two okay so we need sis socket.”
    • “…our program works fine this far but at the moment it’s just a proxy server client it’s not doing what we intended it to do from the beginning…that is what I want to do and that is the next step in this process…”
    • “If you like this episode and want to see the continuation or other stuff in this Channel please uh subscribe to this Channel and hit the like button if you think I deserve it…”
    • “Today you have learned about Linux file system security that there are three parts to it the file permissions targets and the change mode command…”

    In Summary:

    The sources provide a comprehensive look at the development of a Tor tunneling tool, highlighting both the network programming aspects (SOCKS4 proxy, system call interception) and the C programming techniques required to build such a tool. The material also emphasizes the importance of secure coding practices, including proper memory management, random number generation, and safe string handling. Furthermore, background context for other core security topics such as encryption and file permissions are provided.

    C System Calls, Sockets, Encryption, and LD_PRELOAD

    ### What is a system call, and how do you identify one compared to a library call?

    A system call is a request to the operating system’s kernel to perform a privileged operation. To differentiate: first, try a library call using `man 3 <function_name>`. If that doesn’t yield relevant information, try `man 2 <function_name>` as system calls are documented in section 2 of the manual pages.

    ### What are the essential steps to create a TCP connection to a proxy server using C?

    1. **Create a Socket:** Use the `socket()` function to obtain a socket file descriptor. Specify the address family (e.g., `AF_INET`), socket type (`SOCK_STREAM` for TCP), and protocol (0 for the default).

    2. **Prepare the Socket Address:** Create a `sockaddr_in` structure. Set the address family (`sin_family` to `AF_INET`), the port number (`sin_port` using `htons()` to convert to network byte order), and the IP address (`sin_addr.s_addr` using `inet_addr()`).

    3. **Connect:** Call the `connect()` function, passing the socket file descriptor, a pointer to the `sockaddr_in` structure (cast to `sockaddr*`), and the size of the structure. Check the return value; 0 indicates success, and -1 indicates an error.

    ### Explain the purpose of function declarations in C, and why they might be used.

    Function declarations (or prototypes) tell the compiler about the existence, return type, and arguments of a function before it’s actually defined. They allow you to call a function that’s defined later in the same file or in a different file. While not strictly required if a function is defined before it’s called, they improve code organization and readability.

    ### What is a predicate and how are they used within the given context?

    A predicate is a function or operation that returns a boolean value (true or false). In C, this is typically represented by an integer, where 0 is false and any non-zero value is true. In the context of proxy traversal, a predicate might check the value of a response code (like the CD value) to determine if the proxy connection was successful.

    ### How does the XOR operation work, and why is it useful for simple encryption?

    The XOR (exclusive OR) operation compares two bits. If the bits are different (one is 0 and the other is 1), the result is 1. If the bits are the same (both 0 or both 1), the result is 0. XOR is used for simple encryption because applying the same XOR key twice decrypts the data. `(A XOR Key) XOR Key = A`.

    ### How does the RC4 encryption algorithm work?

    The RC4 algorithm involves three main steps:

    1. **Initialization:** An array ‘S’ of 256 bytes is filled with values 0 to 255. Then, using a key (typically 8 to 2048 bits), ‘S’ is scrambled based on the key, using two index variables ‘i’ and ‘j’.

    2. **Key-stream Generation:** The algorithm then enters a loop where ‘i’ and ‘j’ are continuously updated, and two bytes in ‘S’ are swapped. The value of `S[S[i] + S[j]]` is XORed with the plaintext to produce the ciphertext.

    3. **Encryption/Decryption:** The keystream is XORed with the plaintext to encrypt, and the same keystream is XORed with the ciphertext to decrypt.

    ### What security concern is addressed by “whitewashing” the RC4 algorithm, and how is it implemented in the code?

    A known weakness of RC4 is that the initial bytes of the keystream can be statistically biased. “Whitewashing” involves discarding the first several million bytes of keystream after the initialization to mitigate this bias. It is implemented by calling the `Arc4Byte()` function many times (e.g., 500 million times) after the initialization.

    ### How can `LD_PRELOAD` be used to intercept function calls and redirect network traffic through Tor?

    `LD_PRELOAD` is an environment variable that lists shared libraries to be loaded before others when a program is started. By creating a shared library that intercepts network-related functions like `connect()`, you can replace the original functions with your own. This allows you to modify the behavior of network calls, redirecting traffic through the Tor network, while the original program remains unchanged.

    Socket Programming Essentials

    The sources provide the following information regarding sockets:

    • A socket is initialized using the socket command. The syntax includes sock_eynut and sock_stream for a TCP connection. If the socket initialization fails (less than zero), an error message is printed using the perror command.
    • A structure called sock address in is needed to specify IP addresses. The s family needs to be set to AF IET, the Sin port using H ton s for network byte order, and the sin address using inut address.
    • The connect command is used to initialize the actual connection. It references the socket and the structure and requires an explicit type casting to Sock address struct. The connect command should return a zero if the connection/binding succeeds. Otherwise, it returns a -1.
    • The close command is used to close down the connection.
    • When creating TCP client, functions such as sockets to initialize the sockets, connect, close AG tone s, and in address are needed. The include files required are sys/socket.h, netinet/in.h, and arpa/inet.h.
    • The dup2 system call can create a new file descriptor that duplicates an existing one, allowing for piping data between sockets.

    C Library Calls: System Calls, Shared Libraries, and Interception

    The sources mention library calls in the context of C programming, particularly in relation to system calls and shared libraries. Here’s a breakdown:

    • Distinction from System Calls: The source draws a distinction between library calls and system calls, noting that to determine whether a function is a system call or a library call, one should first check the manual pages section 3 (man 3) and if it does not seem right, try section 2 (man 2).
    • Wrappers for System Calls: Libraries can contain wrappers for system calls, such as the connect function.
    • Shared Libraries: The source explains the concept of shared libraries, which contain code that can be used by multiple programs, avoiding duplication. Instead of every program containing its own copy of functions like printf, these functions are stored in a central repository and accessed when needed.
    • Function Hooking/Interception: The source describes a technique to intercept library calls by creating a shared library with a function of the same name and signature as the library call you want to intercept. By preloading this library, you can ensure that your version of the function is called instead of the original. The original function can still be accessed using dlsym.
    • Creating a Shared Library: To create a shared library, specific compiler flags are required. In the makefile example, the flags -fPIC, -shared, and -Wl,-soname are used.
    • Using a Shared Library: To use a created shared library, it can be preloaded using the LD_PRELOAD environment variable. This can be done by creating a bash script that exports LD_PRELOAD to the path of the shared library. After setting the environment variable, the script executes the desired command, and then unsets the LD_PRELOAD variable.
    • Safe String Library: The source discusses the creation of a safe string library to prevent buffer overflows and other security issues related to string manipulation in C.

    Type Casting: Uses and Applications

    Type casting is mentioned in the sources in several contexts, particularly in C programming. Here’s a breakdown:

    • General Use: Type casting is used to convert a variable or expression from one data type to another. This is often necessary when a function expects a specific type, but the provided argument is of a different type.
    • Explicit Type Casting: The source demonstrates explicit type casting using the syntax (type)variable. For example, (Sock address struct*) is used to cast a pointer to a sockaddr_in structure to a Sock address struct* when calling the connect function. Another example is (int8*) to cast a string to a specific type for a function argument.
    • Socket Programming: In socket programming, type casting is essential when dealing with network addresses. The connect function, for instance, requires a Sock address struct* argument, so you may need to cast your address structure to this type.
    • Pointer Conversions: Type casting is often used when converting between different pointer types. For instance, a void* pointer, which is a generic pointer type, might need to be cast to a specific type like char* before being dereferenced.
    • Addressing Compiler Warnings: Type casting can be used to suppress compiler warnings related to incompatible pointer types or different signedness. For example, casting a char* to int8*. However, the source notes that it may be better to change the variable types to regular strings.
    • Volatile Type Cast: When using memory locations, you can use type casting to tell the compiler to not optimize a segment of code. This is done using the syntax: (volatile int8*).

    C Memory Allocation: Dynamic, Safe, and Networked

    Memory allocation is discussed in the sources in the context of C programming, particularly when working with strings, structures, and network operations. Here’s a breakdown:

    • Dynamic Memory Allocation: The source highlights the use of malloc to dynamically allocate memory on the heap. This is essential when the size of the memory required is not known at compile time or when you need memory that persists beyond the scope of a function. For example, when creating strings or structures, malloc is used to allocate the necessary space in memory.
    • Memory Allocation Size: When using malloc, it’s crucial to allocate the correct amount of memory. This often involves using the sizeof operator to determine the size of a data type or structure. For strings, you need to allocate enough space for the characters plus a null terminator. The source uses size of stct proxy request and size of stct s AR for to allocate memory appropriate to the size of the structure.
    • Checking for Allocation Errors: After calling malloc, it’s important to check if the allocation was successful. If malloc fails, it returns NULL. The code includes assert statements or if clauses to check for NULL pointers and handle allocation errors.
    • realloc for Resizing Memory: The source mentions realloc, which is used to resize a previously allocated block of memory. This is useful when you need to increase or decrease the amount of memory allocated to a string or other data structure.
    • calloc: You can also use calloc, but it wasn’t explicitly in the sources. calloc differs from malloc because it initializes the allocated memory to zero.
    • memcpy for copying memory: memcpy can be used to copy a block of memory from one location to another.
    • memset for initializing memory: memset is used to fill a block of memory with a specific value, often zero. This is useful for initializing buffers or structures before use.
    • free for Deallocating Memory: When you’re finished with dynamically allocated memory, it’s essential to release it using free. This prevents memory leaks and allows the memory to be reused by other parts of the program or the operating system. The source includes examples of freeing allocated memory using free(request) and defining a macro un init of free X.
    • Safe String Library: In the context of creating a safe string library, memory allocation and deallocation are crucial. The source describes how to allocate memory for strings using malloc and realloc, and how to manage the size of the allocated memory to prevent buffer overflows.
    • Variable Length Arrays: The source touches on variable length arrays within structures, where the size of the array is determined at runtime. This allows for flexible memory allocation based on the actual data being stored.
    • Stack vs Heap: The source implicitly refers to the stack when discussing buffer overflows, noting that variables on the stack have limited space, and overflowing them can lead to program crashes. Dynamic memory allocation with malloc occurs on the heap, which is a larger, more flexible memory area.
    • Memory Layout: In network programming, understanding memory layout and byte order is important. The source mentions the need to convert port numbers and IP addresses to network byte order using functions like H ton s and inet_addr. This ensures that the data is interpreted correctly regardless of the system’s architecture.
    • Potential Issues: If memory cannot be allocated, assert P error can be used to handle any potential issues.

    C Encryption Libraries: RC4, XOR, and Secure String Handling

    The sources discuss the creation of encryption libraries in C, touching upon various aspects from basic encryption principles to more advanced cipher implementations.

    Key Concepts and Techniques:

    • XOR Encryption: A basic form of encryption using the XOR operation is explained. The XOR operation is applied to each bit of the data with a key; applying the same operation again with the same key decrypts the data. This method is presented for demonstration purposes and is noted to be easily cracked with modern computing power.
    • RC4 Cipher Implementation: The sources detail the development of an encryption library based on the RC4 algorithm. RC4 is noted as relatively easy to implement but requires careful handling to be secure.
    • The implementation involves creating initialization, encryption, and decryption functions.
    • The library is designed to be used by other C projects, so the core code (arc4.c) doesn’t have a main function, but an example program (example.c) is used for testing.
    • Initialization: The RC4 algorithm’s initialization involves preparing the internal state of the encryption engine based on a key. This includes setting up an array and using a loop to iterate through it.
    • Key Stream Generation: The core of RC4 involves generating a key stream, which is then XORed with the plaintext to produce the ciphertext. The Arc for byte function produces a single byte of the key stream.
    • Encryption and Decryption: In RC4, encryption and decryption are performed using the same operation (XOR with the key stream). Therefore, a single function can be used for both, simplifying the code.
    • Security Considerations:
    • The sources mention concerns about RC4’s security, noting that its output can be distinguishable from random data, potentially allowing attacks.
    • To mitigate these concerns, the implementation includes a “white washing” mechanism that discards the first several million bytes of output to avoid known cracking techniques. This involves generating many bytes using Arc for B and performing a volatile type cast to tell GCC not to optimize it.
    • The importance of using a strong, randomly generated key is emphasized.
    • Library Structure:
    • The encryption library consists of multiple files:
    • arc4.c: Contains the actual code for the RC4 algorithm.
    • arc4.h: Contains the structure definitions, includes, definitions, and macros.
    • example.c: A temporary file with a main function that serves as an example program to try things out.
    • makefile: Contains the instructions to compile the whole thing.
    • The header file (arc4.h) includes necessary definitions and structures, such as the structure representing the internal state of the RC4 encryption engine. This structure typically contains variables like I, J, and an array S.
    • Exporting functions: The keyword export can be defined to ensure that certain functions, like Arc for in it and Arc for encrypt, are accessible from outside the library.
    • Installation: The source outlines how to install a created library, including copying the .so file to the appropriate library directory (e.g. /usr/lib/x86_64-linux-gnu/) and the .h file to the include directory (e.g. /usr/include), and running ldconfig to update the system’s library cache.
    • Safe String Library: The source also discusses the creation of a safe string library to prevent buffer overflows, and a concat function is presented. The length is checked and if needed memory reallocated with realloc, and an M copy function is defined and used.
    • File Encryption: The source describes the structure of an encrypted file including padding bytes, password hashes, and encrypted content.
    • Random Number Generation: For cryptographic operations, it’s crucial to use a secure random number generator. The source mentions using the get random system call with the GRND_RANDOM flag to obtain cryptographically secure random numbers from the entropy pool. The code handles the possibility of the entropy pool being empty and includes a warning message for the user.
    • Key Retrieval: When coding an encryption program, you will need a way to read the encryption key from the command line, and you don’t want to echo the key on the screen. This can be done using functions from the termal.h header.
    8 hours of C coding projects: Cyber Security
    C Language Full Course in 50 HOURS with Practical (Beginners to Advanced) | 2025 Edition

    The Original Text

    what’s up guys today we’ll code something really exciting we’re going to be H creating a tool called talyer it’s a command line client for connecting to the tour privacy Network when you run a CLI command for doing a network call for example curl the following thing has happens the connect function is invoked and the uh program establishes a TCP connection to the remote server and then the communication begins but with this tool you’ll be able to put the word talize in front of any command which does a network call taly Will intercept any calls to the connect function and execute our function instead the traffic will be redirected to a local proxy server which is a part of the tour software it will connect to the tour Network and then to the destination server effectively masking your identity and helping you to stay private on the internet and the best thing is coding this is easier than than you might think let’s get on with it okay guys welcome to this episode the first thing we need to do today is we’re going to create our own uh Pro server client so this uh Proxes it uses a protocol named Socks s o ckss and there are two different uh protocol versions version four and version five and the the tour Network and the software supports both these versions version five is a little bit more complicated but version 4 should be very easy to implement and it will be perfect to do it in C so that’s the task of today creating our own client for that sock proxy and use it to connect to the tour Network so how do we start I’m going to start by logging into my code Planet server like this and prepare my screen as I usually do uh today I’m not going to be coding in Naro or VI like I usually do this is a little bigger project a little bit more ambitious could do it in VI even though it’s a big project but uh I’m going to be using um vs code today actually [Music] I’m going to do my wild true command so I don’t accidentally close down my screen window like this um and since I am using a remote server I need to somehow either upload my uh C files and stuff to that server or code remotely in V code somehow and I’m going to be using a tool which is called the sociopath SCP client like this if you want to download sociopath SCP client it’s a tool that uses the SCP protocol which is basically installed on on every server uh to uh upload and download files and subdirectories and there’s also a remote file editing feature that we’re going to use today okay so let’s begin there I have started up the program which looks like this so I connect to my code Planet server and I go to my code folder so on the left side is my local hard disk drive and on the right is uh the files and directories on the server so I’m going to right click and create a new directory which I’m going to call talize this and now I’m going to select the toriz I’m going to right click and I’m going to click open in editor then it’s going to download uh everything in that uh folder which is currently empty but if it were any code files in that folder it would download it to Temporary directory and open it in this code and each time you save or create a file or a directory inside of V code it automatically updates on the server okay so now I have this emptied here so I right click and create a new file which I will be calling talize C and I will also create a tor lies. H like this and I will Begin by putting a small header so talize Doc and I will include SD iio create a main and this time I will type out the longer signature for this uh main function that is the argument counter and the actual argument pointer like this because I’m not going to be using that in the final version but the client that we’re going to code today uh that will be you it will be used like this so if we run it by doing slash toiz we’re going to enter an IP address like 1 2 3 4 and a port so this uh tool will uh connect to a predefined uh proxy server we’re going to put that in our H file let’s do it right away toal light. and let’s put the include in here instead and in this file we’re going to include our local file so when the file is in your directory you use quotes around it like this and I save this file now if we go into the sociopath window we can see in this status bar down here at the bottom T.C has changed successfully updated to server and if we go into our terminal and go into the directory and check the contents of this file we see that it has uh updated the H is not here yet because I haven’t saved it it uploads on save so let’s do that and with regard to the proxy server I will be using the default values for uh the tour package and that will be using the IP address of one 27 0 0 1 that’s the IP address of Local Host uh and let’s call this proxy and I will also make a constant definition for the proxy port which is 9050 as a default setting save and just to verify now we should have both of these files here right so both the C file and the H file great [Music] so let’s just create the most basic things first I will create a CH pointer for the host name that is the host name that we want to connect to at the end so to speak the server that we want to uh connect [Music] to and we also need to have the port number let’s just do an in for that yes okay so first I want just check that Arc if that is less than three which means that we don’t have two arguments specified on the command line then I want to print to a file descriptor which is called standard error which is uh used for error messages it’s like printing to the screen basically and then we want to do like this usage Post Port like that and as an argument we’re going to give arv Z so arv Z if we on the command line specify do/ talize 1 2 3 four and Port 80 then this is AR v0 this is arv1 and this is arv2 and this is an error so we will return minus one and if we have our arguments we will point the post toward towards arv1 and we’re going to set the port to and we can’t just do it like this because the port is an INT and this is a string so we need to use a function which converts a number in a string form to a regular number a2i let me just check if that requires an include file and we do that by doing Man 3 a2i and we need SD libh which I will put in our header file include STD libh and I will also put in [Music] string.h and uni std. H these are the four that I always put in every C program that I do let’s line up this a little bit better like this okay so how will this work we need to figure out how the proxy protocols socks version 4 uh how does it work so let’s go to Google and if we want to have the technical specification of a network protocol we do like this we search for the uh protocol name socks 4 in this case and we add RFC that stands for request for comments and is a the standard way of describing an official uh Pro so that way you will always get the right one and I’ll take the first one here and increase the font size a little bit this is not a huge file some of these rfcs are very big but this is quite a simple protocol so there’s a two step process first you make a TCP connection towards the proxy server like like any other server like exactly as you did in my web server video and in the uh TCP client video then when we are connected we need to create a network packet which looks like this so from left to right there is a one byte field that is 8 Bits for the VN number and as we can read here that’s a socks protocol version number and it should be four then we have something called CD and CD is the socks command it’s a code for the command and should be one for Connect so there are two different uh types of operations that you can do through so 4 it’s a connect operation and a bind operation so basically a connect operation is when you connect the outwards and a bind is when you uh prepare for an inbound connection towards you uh we are going to do a connect so we will put a one in that field uh then we put the destination port number and we need to format that port number in uh Network bite order which is basically that we switch we we cut off cut up the 16 bytes in two parts and we swap them and same with this destination IP but this is a 4bit 4 by field so 32 bits uh regular in size and that’s where where we put the IP address of the uh remote server that we want to connect to and then we need to put a user ID and I will just put talize there doesn’t matter and then we need to end that uh string with a zero byte as usual and that’s basically it we send send that the packet we get a reply which looks like this and the only interesting field is this CD field if that is 90 then the connection has been established and then you can just send whatever you want if we get another number than 90 then something went wrong and we need to deal with that um and then we will send some data just to see that it works so that is what we need to do okay so I will do like this I will copy this and inside our header file I will create a comment block and paste in this this [Music] one I want the last line as well so I see the number of bytes think I need to change the size here okay this way we see enough but in order to be able to create a structure that corresponds to this design we need to be able to create fields that has the 8 bit size the 16bit size and the 32bit size so let’s start there we will use the typ def command to create our own variable types which will be called int 8 int 16 and so on so if we begin with the in8 that’s basically an on sign Char in see that’s 8bit size so we’ll type type def unsigned Char and then our name for it in 8 then we need the 16 bit size and that is an unsigned short in we call it in 16 and then we need a regular 32bit int so that’s an unsigned int I’m going to call it int 32 okay so now we have the different parts that we need now we’re going to create the actual structure for this packet so we’ll create a struct which I will call proxy request and the first is VM so in8 VM and the next is CD which is also an 8bit then we have the destination Port which is 16 is port and then we have the 32bit destination IP field and then we have the user ID which has a variable uh size but I’m going to create a username of seven characters because that way we can have uh an 8 a 64bit Str variable here which ends in a zerobyte so that’s why seven and not eight so basically I will do unsigned J user ID 8 and this is all we need for the first uh structure let’s create the other one at the same time this one is a little bit smaller so struct [Music] proxy response and we’re not going to be using all these fields so if we look at this one the VN is always zero and the CD will have the code so the CD is the only interesting field here because the remaining fields are ignored so destination port and destination IP are ignored but we still need to have them defined because we need to have the right size of this package so I will do do it like this I will start by creating an 8bit integer for the VN and 8 bit CD then I will just do in 16 and an underscore character and then int 32 and two under score characters we could name these according to this but U I think this show clearly shows that they are not important okay so now we have our two structures we can remove those comments and make this a little bit bigger again and I want to create a type def for these structures so we don’t have to type the whole proxy request every time and I will just call this wreck with a Big R and same here type def stct proxy response and this will be rest with a Big R okay so now I have now we have prepared everything we need basically in this file and we do need a couple of includes though because we are going to use the following functions we will have uh sockets to initialize the sockets we’re going to have connect and we also need close AG tone s and in address so remember what I told you about the network bite order so if we have a port number for example like something like this in U binary so this is a 32 bit no sorry 48 this is a bite so if we do like this let’s say this is a port number and I don’t know exactly what it corresponds to but let’s say for instance that it’s 9050 because it’s a 16 bit field so it looks something like this then we need to copy this right part and put it to the left that is Network bite order that we have the most important bits first and that is what these two functions are for HT s does it for the U the port number and the init address takes a string and creates a big so basically it first take this IP address and translates it to a big number and then it makes this network by order so these are the functions we need uh perhaps I have forgotten any uh other ones but that will be clear when we get to that point so let’s find out what um include files we need let’s begin by socket we do man to socket and why two because this is a system call that’s why how do you know if it’s a system call or a library call try a library call first three if you don’t get a hit or if you get a hit that doesn’t seem right try the uh the two okay so we need sis socket. [Music] I’ll just copy it right [Music] on this and then we need the connect that’s also a system call so Man 3 no man to connect and that’s the same we don’t need it again and what else did we need uh closeth I think that’s un SD that we already have but let’s see so the close that is also a system call and we use it to uh close down uh the connection can also be used to close down a file yeah un SD we had that already and then we need the hton s and IET address so man this is three so h t s this one and finally inet address also a library call so three here we need a couple of include CIS socket we do have already ARA inet we do also have but not netet okay so let’s see if this compiles since we are using a couple of files I think I’m going to create a make file as well so I will create new file and I will name it make file with a big M and then I will just put in [Music] all JCC talc doraliz we’re going to be adding a lot of stuff here later on but for now now this how to do it so let’s uh save and when we have a make file like this then we don’t need to issue the GCC command every time we can just do make and then it will try to compile okay in okay typo so so let’s go into the toor realize. C and this should be an if not an in let’s save and we’ll run make e this time it compiled our tool okay so the next step is connecting to the proxy server because we’re not going to create a TCP connection directly to this host and Port that we specify on the command line we are going to connect towards [Music] the the proxy IP address from the h file and the proxy port 9050 so that we have done before creating ATP client and it’s exactly the same as before so I’m going to make it quite fast if you need to learn how to do that you can watch either my TCP client episode or my creating your own web server series I will explain by haste though okay so we need a couple of um variables first of all we need an INT which is called s for the socket file descriptor return value we also need a structure which is called sock address sock address in and I’ll call this sock that’s where we spe ify all the IP addresses and stuff um okay so let’s start by creating our our socket so s equals socket and this is pretty standardized we always put in sock ey nut and second argument is sock stream for a TCP connection and then a zero for the third argument and if this s is less than [Music] zero then I will use the P error command to easily print an error and we will specify which function that produced that error and then I will just return minus one when we uh create the final version of this I’m going to use more accurate error codes but for now we’ll just do minus one for everything then we will create we will prepare our structure and that’s three things we need to add in order to make atcp connection first of all we need to put the S family to AF IET we need to put in the Sin port and use the H ton s so we get it in network by order and then we will just put in our Port variable here and finally we will put in our sock sin address s address and that will be equal to inut address and our no not our Port it should be our proxy port and it should be a our proxy IP address nothing else okay so these are the three things now we need to initialize the actual connection with the connect command so we do connect and we reference the socket uh the second argument is our structure and we need to create an explicit type casting because we need to change it to Sock address struct a pointer to a sock struct and we also need to send the reference so let’s put an % there and the sock and then we need a size and I will just do size of suck that thought to do it okay so this line will connect to the server but I will also need to do an if statement so we see if it succeeded and this should return a zero if it works if we wouldn’t remember that we can go into the command line and do man to connect and go towards the bottom and here we will find a section for the return values if the connection or binding succeeds zero is returned otherwise minus one so I will just do a simple if statement there’s no need to save this to a variable so if this is not zero something went wrong and then we do p error connect and return minus one otherwise we are connected to the proxy server so I will just Echo that to the screen so we know what’s happening then I will close the connection because I want to see if it works so close s return zero okay let’s see if we did something wrong make it compile on the first run that’s not every time and let’s run it and see what happens right we need to put some something here we’re not going to be using that information at the moment connected to proxy great so it works so now we have successfully created our TCP connection towards the proxy server and the next step is to create the uh proxy request packet according to this structure that we created before we haven’t created any function declarations so let’s do that as well so we have a main function takes in an in and an arv pointer and when I create those signatures sorry chart of course so if we look at our regular main function we use this format right here so H Char array of pointers but when I create the type signature I usually use this format doesn’t really matter okay so that’s the only function that we have this far our other function is going to return a pointer to a request and let’s name this function request and as argument we’re going to take in a sh pointer which is our destination IP and just a regular in for the destination port and let’s make both of these counts as well the count keyword means that we cannot change these variables inside of the function so it’s just input values so this is the signature I’ll copy this and then I will strip it down so it looks like our main one because we don’t need to have the names of the variables when we do a function declaration and why do we do this function declarations do we have to no we don’t we don’t have to but imagine that we put our main function in our C file at the Top If we then and try to reference the request function it’s not going to find it because it has hasn’t been Define yet but if we put our request function on top of the function declarations then it will work so that’s one reason but I think a more important reason is so you can have like a um a better look you can just watch the H file and you see the entire structure in a very good way so always do this if you have a multiple files or a Big C file uh okay that was a small parentheses sorry I copied over this [Music] one there we go and then we go into here and we will create this request so what do we need in order to do that well we need to allocate the memory for this uh request uh structure that we’re going to uh turn and we are going to reference the length of the structure a lot of times so I’m going to create an alias that or a macro and you do that using the Define and then you give it a name I will call this [Music] Rec size and uh what is Rec size it is the size of stct proxy request and let’s create one for the other one as well though Define uh rest size response size and that is size of stct proxy bon in that way we don’t have to manually type out this as soon as we need to reference the the size of the structure and um semicolon at the end oh I misspelled there we go okay so back to the C file again and I’m going to create a request pointer I’ll just call it recre sorry and I’m going to start by uh allocating the memory for this structure so request equals Malo re size like this and now we’re going to fill this structure with the correct data so let’s bring up [Music] the RFC again so the first thing is the VN and the VN should be four so w VM equals 4 and if you’re not familiar with this Arrow that’s basically the same as the dot format but when you’re using a pointer to a structure you use this um Arrow to to indicate that we need to grab into the the reference in order to get the value or set the value in this case okay so VN is four then we have the CD and it should be one because we’re making a connect request so Rec CD = 1 then we have the destination port and we need to put it in the correct format so wck this Port equals and now we use this Hon s function that I talked about before to switch it to network by order and uh is the destination Port then we take the destination IP so w destination IP equals in address destination IP and then we need to have a null terminated string with our variable and I want it to be eight characters so let’s create a definition for that find username toiz cuz we need to remove this e 1 2 3 4 five 6 7 and then a ZTE at the end so so we will use I will use string copy to copy into the W username the usern name and the maximum size is seven and then it will uh add the zabte let’s do it okay so now we have prepared this structure and now we will simply return it like so and now it will be very easy to to hand handle this because we have a function which just creates the entire data that we want to send and we know the size of this structure so we can just use the right system call in order to send it okay so now that we have our function which creates the packet that initializes the proxy connection now we’re going to use it so let’s go into our main function and let’s create a pointer of our structure request type so we can use it when we want to send the data and instead of just closing the connection like we have done here we’re going to set our request variable and use our function and our request function takes two arguments it is the destination IP and destination port and we do already have variables for that it’s the host and and Port variables so we’ll just use some so host and Port like this so now the wreck variable is pointing to a toour packet and we just need to send it using the right system call the first argument is our socket file descriptor which we named s uh the second argument is [Music] the is buffer and I think we only need to do wreck perhaps we need to do yeah we probably need to do a type definition type cast I mean but let’s put put it like this to begin with and watch the warnings and errors if when we compile it that’s usually the best workflow uh and we need the size of the packet and since we know that we we always want to use a 8 by an 8 byte buffer for the username we have a constant size of our uh request packet so we will just use that uh definition that we put in here somewhere it is I think we created a macro yes Rec size that’s the one that is the size in by for how big this packet is so now we send that packet and the next step in the process if we look at our RFC it is accepting this structure back so we can look inside of the CD property and uh look for the 90 code so how do we receive this one well we did use write in order to send the data and will use read to receive the data uh and for that we need a buffer so let’s I think the easiest way will be to just create a variable on the stack for that so buff and then we’ll put the response size as the number of bites and before I use read I always want to make sure that the buffer is empty so I will M set the buffer with zeros and uh use the rest size number of zeros so now we have a clean buffer that we can read data into um yes so let’s do read and the first argument is the socket file descriptor second argument is the buffer and the third is the size like this and if this read operation returns something less than one because the number of bytes should be [Music] returned then we know it the operation has failed and we need to show an error sorry I’m a little bit used to the JavaScript strings there we go and let’s uh free [Music] the the the buffer uh no not the buff free the uh request packet so we don’t have things line around on the Heap and let’s close down the socket file scriptor and return minus one for now so this is if the read operation fails if it has succeeded we should have a packet that looks like this in our buffer but we can’t easily access the values inside of it if we only have a string pointer so we need to create another pointer of the correct type which is our uh structure for the procure response so we will create a rest as well as the wreck and we should just be able to point this towards the buffer and that’s what we’ll do so rest equals buffer I think this should be enough and now we should be able to grab this value the CD value and I like doing it like this I will create a an INT which I will call succeed success and this will be a bullan variable but as you know we use ins as booleans we can use Char and other types as well but usually it’s in and uh this will be used as a predicate I’m not sure if you are familiar with the term but a predicate is basically a a a function or an operation that returns true or false and uh this is American English I think in the British World they use the word property for this but since we already use the property term when we describe other things I think the predicate is a better term anyhow then we can do something like this so we set success equal and we go into this structure and we check for this CD value now we’ll put this in parentheses and we do like this so what does this mean this means that if the CD is equal to 90 then success will be equal to true if it’s not 90 success will be false which means we can do like this to see if it has worked or not and then I want to print out a an error message of my own so I use the fprint F to the standard error way and I want to say something like unable to Traverse the proxy error code and then the error code I need to divide this a little bit I’m not sure you know it but if you have a large string you can always divide it by lesser by smaller strings uh and put them on different lines make sure to encapsulate them in quotes on both instances and then we will show the rest do c the rest to CD value like this and we can also do yeah let’s close the S and let’s free the w return minus one and unless this if Clause happens we have successfully traversed proxy so let’s inform that with a print F at least for now perhaps we will remove these messages when we are done okay so [Music] successfully connected through through the proxy to we will have a percent s colon percent [Music] D and then I will use host and Port like this and now I will close down the connection when we do the when we finish this uh program off we will not be closing down the connection but since we are only checking right now if it works if we are able to connect through the proxy we can close down everything and terminate when we are done so this code will be removed in the final version and we will free the W and return zero like this H the indentation seems to be a little bit off well we’ll see if we get an error okay so let’s compile this and see what happens okay uh and when we are troubleshooting code especially when we have coded quite a lot of lines of code since we last uh compiled always look at the first error because sometimes if you fix the first error all the other errors goes away so don’t get discouraged when you see a full screen of error messages like this just focus on the one at the top uh so what does it say w has no member named username interesting so let’s go into our H file and see what we’ve got user ID okay yes of course so where were was that that’s probably inside our request function right yes here it is so user [Music] ID like this okay and before I run make again I press enter a couple of times so we get a barrier that way it is much easier to see where the last couple of error messages stops and the new batch starts okay so assignment to rest star from incompatible pointer type rest equals buff okay that’s the one I was a little bit unsure about remember and I said let’s uh compile this and see what it says because in some of these cases the C compiler will perform an implicit type cast in this case and uh work it out anyway but not this time so okay so rest is a struct pointer and buff is a string pointer so what if we were to just [Music] do res like this let’s try that first seems like it worked okay so close s data definition has no type or storage class that’s an interesting error message data definition has no type or storage class close s in close in FD uni SD do we have all our include files I have never seen that error message before you SD yes didn’t I call that variable s yes and that’s an INT in in it was only a warning but very weird warning perhaps something else is wrong in its proximity if success F print F and the parentheses then we have the string and then the end parentheses close s what line did it complain about 94 okay it’s not it’s not this one it’s complaining about this one well uh there is okay so let’s [Music] see if success do and then we have this close s close yeah this shouldn’t be here okay let’s do this again okay it compiled let’s see if it works so what shall we connect to I will just do one of my web browsers and you might have noticed that we didn’t put any DNS related stuff in this one so I can’t just put in www Network technology.org or something like that that’s something that you probably can add by yourself see that as an extra task and but for aove of concept it’s not really necessary okay so I will take the IP address of my web server and let’s run talize against that on Port 80 and if this works we should see a message that we have successfully connected to the proxy and we should also see a message that we have successfully connected to the end host through the proxy connected to proxy successfully connected through the proxy to blah blah blah blah blah blah okay very nice so this has accessed the web server through through the tour Network and let’s add uh let’s add some functionality so it can send some data and read some data so we can see that it can communicate with the end host as well that is also stuff that will be removed in the end in the end result so let’s create another buffer let’s call this temp and let’s do [Music] 52 since it’s only temporary I will not think much of it so here we are successfully connected and now I want to send something so since I’m connecting to a web server I can use the head command just to grab the information about the web server versions and stuff like that that’s quite easy to do so I’m going to use the SM print F in order to create the buffer but first I want to use the M set in order to zero the entire buffer so no not I need to remember I call it temp and zero and the number is 512 and then I will do SN print F and we are going to put the result into the string variable the buffer that we call temp and we won’t be writing more than 511 characters and what do we want to put there so let’s do head [Music] HTTP like this and we’ll end by r [Music] n and on the next line I will put in host Network tech.org and and if you wonder what this RN is sorry that is the Windows standard for new l so this R thing is a carriage return which jumps down and goes to the left uh or it goes all the way to the left and the N is as usual the Line Feed Okay so now the buffer is now the buffer contains this [Applause] data and then we will just simply send it so write s temp and I’ll do string length of temp like this and then I want to zero out the buffer again or not the buffer the temp and then we want to read the results so we read from s into temp and no more than 511 bytes and then we’ll just print that to the screen with a regular print s like this let’s put it in single quotes as well so we see if there’s something weird going on that’s a good tip by the way like if there’s a line feed before the the data or something like that then we will see it like this so this will be on one line and this will be on the next sline okay save and now we will compile and let’s run it again and this is the response from the web server as you can see it works we can we are able to communicate through the tour Network and if I connect to my web server we should be able to check the logs and see what IP address the requests came from more log P here we are and let’s do tail D3 access access. look okay so here is our head and if we grab this IP address we see that it’s it’s some kind of German uh address and we can also do if we restart the tour server so we do Etc in tour restart as root [Music] restart like this then we issue the same command again we did get the output like before and if I check the logs once again we get another another IP address this time and if we do a host on that IP address we see that this time it’s in the Netherlands so our program works fine this far but at the moment it’s just a proxy server client it’s not doing what we intended it to do from the beginning you remember I want to be able to do something like talize and then run any [Music] command like curve against some IP address and then I want to in intercept the connection I want to run this command as is but I want to intercept the con the connection that the actual program does and run my code instead so it tunnels through the tour Network any program that we want to run so we can do talize and put anything here we could do like if we have a Firefox installed in the same directory we could start Firefox with toiz and then it will be tunneling through the Tor net work and we could do tell net or SSH that is what I want to do and that is the next step in this process it seems really Advanced but you will see that it’s quite quite a bit easier than one might think so what have we learned today today you have learned how to create a Sox version 4 client and use it in order to connect to the tour Network and next time you’re going to learn how to create this Nifty little tool that I called toy if you like this episode and want to see the continuation or other stuff in this Channel please uh subscribe to this Channel and hit the like button if you think I deserve it and uh thanks for watching thanks for today welcome back everyone to today’s class today we’re going to talk a little bit about something called exor so exor is an operation you like you can do PL plus and you can do minus and then you can do xor but exor uses two streams of bits and it produces different output bits depending on the input so if we have two zeros then the result is zero if you we have a zero and a one then the result is one no matter which it is which but if both are one then there it is zero so why is this useful well this means that if we use this technique in order to encrypt something then we can decrypt it if we Supply the cipher text with the same key as when it was encrypted this is a very basic form of encryption that uh is only for demonstrational purposes it’s quite easy to crack with today’s Technologies and computer power however it’s a good example on how to use exor and in this example I will only make it so that you encrypt one one single character and when you know how to encrypt one single character there shouldn’t be a problem for you to modify the code so it can be able to encrypt any length but only one character in this example all right so let’s begin by creating an exor doc file and we will also have a couple of definitions we will Define the key which also will be one character and we will Define what we want to encrypt so let’s define the key as the character X let’s do big X and and then we will Define the clear text as the letter A so we want to encrypt the letter letter A using the key X and we don’t need a whole lot of includes I will just put the standard input output age Library and in order for us to be able to see what what is happening I will create my own function called print Char which will print the character and the heximal value and it will also print a text string describing what we are printing and this will just be a single print F line something like this so we will take the [Music] character and show its asy character code and uh we could do hexad decimal but I think yeah let’s do hexad deal and it will take three arguments the text describing what we are doing and then the character twice so we’ll print the actual character and its heximal representation and I will put a0 X in front of it to show that it’s hexadecimal and that’s all okay then we go to our main function where we will do the magic so to speak we will click create a couple of Shar one for the clear text one for the key one for the cyer cipher text hard to write write that word and one for the new clear text because we will decrypt it into a new variable okay first we Define the clear text as our clear text definition this one and we will use our print Char to print the clear text before we do anything with it then we will Define the key as our constant key and do the same we will print that on the screen and then we will do the actual encryption so the cipher Cipher text should be equal to clear clear text xor key so this little Char uh carrot character here it’s is is not uh uh what you might think it is uh sometimes we use this carrot character to do when we do like x to the power of five or something like that but in C the carot character is equal to the exor operation okay so now we have created the cipher text variable containing the encrypt text using the key now we want to print the result Cipher text and cyer text and finally we’ll try to decrypt the text into another variable and this time we will take the cipher text and xor the key so as you can see the exact way that it goes forward when we take the clear text uh X or the key producing the cipher text we now take the cipher text xort the key to produce the clear text and then we we will use our print Char function to print our new clear text and that should just about be it so let’s compile this one oh I did something wrong I main that’s not right there we go okay now what line 47 ah I added a parenthesis too much so let’s jump to 47 okay it’s outside of the text but I did see it on the message where is it ah right here that shouldn’t be there all right now it works so let’s run it okay so from the beginning we have the letter A as a clear text and that is 41 in HEX and we have the key X which is 58 when we combine them together with with an exor operation we get a cipher text with a hex representation of 19 and no asky representation and then we exort the text backwards using the cipher text and the key and then get we get a new clear text with the letter a 41 so our code works just fine should be cat not CL car okay so we do two definitions we create a simple function in order to print out the results we set the clear text and print it we set the key we print the key then we do the encryption algorithm so to speak using clear text xor the key and printing that out then we do it backwards we the cipher text exort the key and get the new clear text and press print that out so today you have learned all the race to the exor operation in C thanks for watching and thanks for today what’s up guys in this episode we are going to code our own uh encryption Library it is uh Loosely based on the arc4 cipher but with some improvements which makes it more secure we’re going to expose a couple of uh functions from our library and it’s an initialization function which takes a key as an argument there’s a encrypt function and there’s a decrypt function and finally an un initialization function so it’s very easy to use and U let’s get [Music] started hello everyone and welcome to Today’s Show today we’re going to code our very own encryption Library using the arc for uh algorithm when talking about encryption that is uh one of the more easy encryption ciphers to implement but it’s a little bit bigger pro project than we usually do so I will not be coding inside of the terminal today I will do most of the work through the is code so let’s begin by launching the sociopath SCP client so we will be able to code live against the server I will just go into my I will put it in my temporary directory and I will create a new directory and I will call this Arc for spelled like this so the algorithm is written like this rc4 but it’s pronounced arc4 so I think that’s a good name for the library so I’ll simply create an empty folder and I’ll right click and open an editor then I will have access to the entire folder ins side of vs code like so and I will minimize my sociopath and close down this and I will also log into my server and attach to my screen or uh I will create a new screen instead and I will configure it and as you WR V of and as usual I will write a simple bash script like this just so I don’t accidentally close down this window and terminate the screen so let’s go into my temp directory and go into my arc for and here we are an empty folder so what do we need I will create a two files or three actually first I will have the actual code the ark4 doc like so and as I save we can see here it’s successfully updated to the server and we will also need a Arc for. H for our structures and includes and definitions and macros and such and to make our life a little bit easier I will also create the make file which is going to compile the whole thing and actually I will create a fourth file as well this is just an temporary file we won’t need this file when the project is completed but as we are implementing this encryption it will be easier if we have an example program which we can use to try things out and I will call this example. C because we are creating a shared Library so this Library will be used by different uh c pro projects and that means that the arc for. C file will not have a main function so this example. c will provide our temporary main function so we can run it all right so in the make file I will simply Define the stuff that needs to be compiled so the first thing we will be Ark for. o and you write it like this so the file that you that’s the Target and then a colon and then you write the dependencies so this file will depend on Arc for. C like so and then you Tab and you write the command so I will do GCC d c AR for DOT C like this and I will also turn [Music] on optimizations at the highest level as well as log messages and when that file has compiled successfully we will have an arc for. and then we will create the actual Arc for Library so this depends on Arc for. o and I can’t really remember how [Music] to let’s see all the flags necessary to create the shared Library so I will check how I did it in my toiz make file and I will simply copy this part right here so I will do GCC and we are compiling Arc for. o or linking actually and the output will be called Arc 4.so that’s the extension for a shared library and we want the uh optimizations and the log and then this additional Flags necessary for a well for a share Library [Music] okay there we go so after those two steps our library is compiled but I will also have the example do o dependent on example. C GCC d c except exle let’s see and I will turn on op and well and when we have the object file we can compile example which will need example. [Music] o and then we simply do GCC example. o Dash o example wall two and I will also create a clean which simp removes everything besides the source files so all o files allo files as well as the example binary executable and then I will just tell the make file what we should do as a default when we run the command and I want to compile Arc for and example so this is our make file if I didn’t miss anything I think we should be able to let’s just go into the temp and the AR for and I will set this to my home so the prompt won’t be so big like this and I didn’t save the H file I think and the example and make file there we go Arc for make file Arc for. Ag and example so I should be able to run the make now and we get a reference error for the main but the do all files should have been created yes they did so everything seems to be working even Theo file did be created even though everything is just empty source files and if we do make clean we’re back to where we started okay that’s a little bit of administrative work but it will pay off when we need to recompile and debug our code I’ll close down the make file because we don’t need to do much with that and I will actually start with the example file because if if we create the example first then we have a kind of a road map to the different functions that we need to create later on so I think that’s a rather good way to start I’m going to include the arc for H oops or for H and inside that I will have my regular definitions so I usually start by putting in the STD iio that will be removed later on because we’re not going to use any of these libraries but during development I think it’s easier to have all the usual standard libraries ready to go like so okay so how will this example file work um I’m going to start by just creating function definitions so we do everything in the order that you should even though this is a small file so we’ll have an in main with no arguments and that that’ll be all for now so I’ll create the actual all M and I never seem to learn where to find my curly braces on my Mac all right here they are so I’ll will create I will make this file a little sloppy and easy to work with because this will not be a part of our production code so to speak so I will just do it as easy as it can be for myself so I’m going to create a couple of pointers I will have one for the key and I’ll have one for [Music] the uh Source text that we want to encrypt I will have one for the destination text [Music] and I will have one additional pointer for when we decrypt the encrypted text so let’s call this encrypted instead and this decrypted that’s a little bit more obvious and I think I need to make this a little bit smaller I hope that won’t be a problem for you okay and I will just Define this statically so I will set the key to let’s [Music] see something easy like tomatoes when you run this code for real you should always create a a real encryption key so this can really be anywhere from 8 Bits to 2048 bits according to the standard but this will do as an example and the text I want to encrypt is a part part of a Shakespeare poem shall I compare the to a summmer day okay we will also need to before we do that I need to define a couple of type definitions because I’ll be using eight bits in Gears and I will use 32 bits and possibly 16 so I’m going to define those first so let’s define [Music] um we will do unsigned char that is an 8bit value and I will call this inate and not defined by the way this should be a type definition so a type definition is when you create your own type everything you write is what the source name is and the last one is the destination okay so the next type definition will be a 16 bit int and that is defined in C as an unsigned short int and I will call it int 60 and finally we need an 8bit uh variable as well and I will type this as an unsigned chart in8 [Music] um oh sorry I have done that already the only thing we have left is a regular a 32bit integer and uh that will be well a regular unsign in like this okay so now we have our type definitions and let’s continue with the example main function so we have the string that we want to encrypt we have the key we will also have a um a pointer to a structure which I will call Ark for and I will call this pointer Ark for like this so this will contain the internal state of the encryption engine so to speak and I will Define this as a let’s do it here I will do struct s I usually prefix my structures with an S that’s a stylistic choice though uh so s Arc for and what will this contain well we will we will actually use the Wikipedia page it’s a very good Wikipedia page which tells exactly how to implement this encryption not in a specific language like C but with like pseudo code okay so we have this and now that we have the key by the way we also need to size variables so let’s [Music] do in 16 and what do we need we need two size variables so let’s call those size key and size text and I will just use this string length to define those so SK equals S L key and S text equals s l f okay so now I have all that that I need in order to call the first Arc for function and that is called let me do the T function declaration it will it will be called Arc for in it because it initializes the arc for structure so this will be of type Arc for pointer and it will take two arguments it will take a key let’s do it like this unsign CH no let’s use the orate it it’s not really an integer because this is a string but every every character is an integer so it will be okay I think so in8 key in because if I don’t do it like this if I do sometimes Char and sometimes in eight and then I will probably get this signedness wrong and I don’t want that and we will have an in 16 for the size of the key and I don’t need those in poter in 16 right then we go back here here and we will set our ark4 equal to Ark for in it and we send our key and our s key like so and this is a function that might fail but that’s very unusual so I won’t care for that during this example program but if you write a real production grade program check if this Arc for returns zero because in that case The maloc Returned error otherwise we will get one of these structures back and then we are ready to encrypt let’s add some prints as well so in initializing encryption and I want to have a way of putting this to the screen instantly so I will create a definition which show which call F and I’m not putting this into the arc for. because this is not something I need in the in the actual uh end res in code this is just for convenience so F will be F flash SD out and that basically flashes the standard output buffer so that if I do a print F like this which not which is not ending in a new line it will and if this takes a couple of seconds to initialize then this text will not be printed before this delay which is which kind of defeats the purpose so I will put the F right after like this and then down new line okay and then we will let print out the input first so I will put it in single quotes [Music] and let’s do it like this a new line and then an AR an arrow and this is the front text like so then we do the actual encryption so we will use our encrypted variable so encrypted equals Arc for let’s define this first so this will return a string pointer but I will call it an int8 pointer and it would be called Arc for encrypt and it will take two arguments one which will will be an in8 pointer so the string that we want to encrypt and a size in the form of an 16bit integer like so pretty similar to the initialized function and the arc for uh encryption works like this you you don’t need a specific decryption function because if you try to encrypt the encrypted text it will be decrypted so then it goes backwards so with that in mind we can just create a macro which will be called Arc for decrypt with two arguments X and Y and this will just call Arc for encrypt with X and Y so it’s not really necessary but [Music] it makes it a little easier to use and in order to make this encryption function work we need another function called Arc for bite which produces one single character of encrypted text so this will be an INT 8 and not a pointer just a value now that we have our data types and our function declarations done we can continue with the example. C file so the encrypted variable will be equal to Arc for encrypt and we will send in the uh from text and we will also send in the size of the text like so and this is a function which shouldn’t be able to fail which means that the encrypted variable will now contain the cipher text the next thing we need to do is create a function which can will make it possible to Output the encrypted text in some format because the um the encrypted text will not be printable characters it will be any number of different integer values and I’m thinking about putting using an output like this so one B will be represented by two heximal characters like this like this so this is one b and then two byes per group and each group will be separated by a space okay so this this function uh will uh will not be a part of the library itself only this example file so it shouldn’t return anything and let’s call it print bin because it’s binary data and it will take in an INT 8 array pointer let’s call this text it’s not really text but whatever and then we will have an in 16 for the size like this and all we need to do is iterate through the text and print those bites two at a time so how do we do that in the easiest possible way there are several approaches but I’ll I think I will just I will just create an in32 as an iterator and I will have an in 8 pointer as well and I need to assert that size is bigger than zero and what is assert assert is a function which checks if this predicate function is is true and if this is not through the whole program halts so it’s quite good to use in situations like this both in this example file because it’s easy and it doesn’t matter really if the program exits and we can also use it in our production code in some places because we are coding a library and the programmer should s the ra right arguments if not the program should hold I think all right so we need to go into this Arc for and include what’s its name it’s assert Ag and in order to get all the functionality we also need to include our number. H like this now we jump down a little bit same here okay so we know that we have an input which is let’s call it input instead that we have an input which is a well which contains something length is bigger than zero okay so let’s do a loop then so four and we will [Music] do let’s make this an in 16 instead that will work better together with this 16bit size so let’s and I want to make this const as well here okay so let’s set I to size and P2 input we’re going to continue the loop as long as I is positive so I’ll just put I here because it will decrease every iteration and it will after a while go to zero and the loop ends and the PO pointer will instead increase every iteration okay so if let’s see I need to check something out so the first iteration then let’s say we have a string which is 32 bytes so I will be I will be equal to 32 and we will output to one B of data then it will be equal to 31 and we will output two more so let’s see I think we could write it like this so if I + one let’s see if I + 1 modulus 2 if that’s the statement is negative so it’s equal to zero in that case I want to print f space and in any case I will print out a head ex a decimal value with two two digits and this is what we want to print out I think this will be correct um so this basically means that if we are even so if I I + 1 is even then we will put the space and we will also use our macro F so it will uh uh print this no we don’t need that by the way because we will end this with a new line anyway so that will flush the buffer this should be all I think and let I have forgotten something but let’s try it out so what can we try it out on we don’t have all these functions [Music] yet so let’s comment this out and this as well and this is okay and what shall we print as an example we can print the key so print bin that’s actually not binary data but it will work the same so we will print the key and S key is the size turn something like that let’s see if this compiles or if we need to remove something else make a lot of warnings type Def unsigned sure expected before unsigned before unsigned uh I have an empty struct that’s probably it let’s just put something temporary here then [Music] maybe it is because of the position sometimes you you need to do one thing before the other Etc uh forgot to end the struct with the semicolon is it still complaining type ofure in if we add our type def [Music] for for struct does that error as well type of struct is ar ar for uh it’s not uploading okay I got disconnected one good thing with the sociopath is that if you reconnect like this you don’t have to do anything else it remembers and continues to serve all of your files so that’s good okay let’s save this again and this one and let’s jump down a bit clear the screen and let’s make it again okay finally pointer Targets in passing argument one of print pin differ in signedness uh uh okay so this is what happens if if I don’t use my in a eight everywhere so where did I not uh here let’s just change this to int 8 and everything should be okay okay we’re down to one screen of errors and warnings [Music] almost does it still uh seems like it needs a type cast because the strings are generally not like these static strings in side of the code they are generally not un so let’s do a typ cast in a poter and same here in poter key ah so SD L needs it as well I could just make these strings signed but then I would have the same problem in the other end instead because the encryption uh standard requires them to be unsigned so let’s just type cast this as well in 8 like so do we use them anywhere else except our own [Music] functions print F shouldn’t care right let’s do it just for the sake of like [Music] this okay let’s try it again at least we have very clear and precise error messages in see did I go to far make clean make S key equals didn’t I save [Music] save why does it okay it’s higher up in the code right in eight star and there we have it okay that should be all right make clean jump down make what does it say this time point or Targets in passing orent one of string length di in different ah I did it in the wrong direction okay that’s kind of funny so instead of in 18er let’s see there there there and there we should just have Char because we have them as int8 but the functions we’re calling requires them to be regular strings so a sign CH pointer okay this time it should look a little bit better I think make clean jump down a bit and make warning pointer Target in assignment from sh to 8 AKA unsigned different sign do so it doesn’t seem to be enough by doing this it this way okay let’s do it the other way then I will undo until I see this change like so so now all of these key and this this will probably not be but here we can do a conversion in the other direction instead and that should be all make clean jump down make okay now we’re talking warning unused variable that’s an annoying message if I don’t want to use my variables I don’t use my variables but okay so let’s do something like key equals from equals encrypted equals decrypted equal key = Z is that enough maybe I should end it with a semicolon operational key may be undefined variable s text set but not used right so it wasn’t enough to mention the key twice this is only set and all of these are used so we need a key [Music] what [Music] about from equals key okay now what s text but that’s an INT right yeah I haven’t used that yet because we haven’t gotten that far these are only warnings by the way but I when I try out my code and I want to remove everything of the sort uh so which is this this is [Music] the text so we will change the key later on let’s just [Music] do s key equals s text equals zero now it should be completely Warning free I believe no one more warning unused variable Arc for okay I haven’t used that I can just let’s comment that out for now make clean make okay finally let’s see if this works as intended example okay so shall I compare the to sumers day and then I am showing some of the key but I am showing half a group here and half a group here what will happen if where is it if I just do I here okay now it looks good it prints out in heximal characters in nice formatted group very nice that means we can begin with the actual encryption code now finally so let’s go over to the arc for uh H and begin working on our structure this will contain the internal state of the uh of the encryption engine so to speak so let’s go to that wonderful Wikipedia article so Arc for wikii and I want the English speaking Wikipedia let’s hide this and make it a little bit bigger for you guys and let’s do something like this let’s use the whole screen I will probably be looking at this anyway so there’s a lot of text here and some of it are warnings that this uh encryption standard isn’t secure but I have read through all of that and I’m not sure if I agree actually well this the thing is they claim that the out put of the encryption is distinguishable to when compared to purely random byes of data and that could be potentially be used to backtrack and crack the encryption and it has indeed been used for example the wifi encryption standard web used exactly this encryption with very small keys and a spe special kind of U seeding algorithm which they were be they were able to crack it in the wild in a couple of seconds but that’s only in combination with a web technology and there has been some talk that in combination with the TLs the encryption standard on the web it’s also not safe and it’s not safe the first couple of bytes which it produces is not safe so since we are using this encryption firsthand in our own code not together with anything else and I will also create a mechanism which will disregard the first like 500 million output bites which will stop all the other cracking techniques so I think with a big enough key which is um randomized in a secure manner I think ark4 is still secure Okay so I don’t you don’t need to read through the whole shebang but those gray information boxes are very good so there there’s two steps Step One is what I call the initialization of the crypto that’s when you only take the key and you prepare the internal state of the encryption engine and this is what you do and then the next stage which happens every time you need to encrypt one bite or more exactly produce one bite of the keystream data so then you do this so let’s start writing now let’s begin by creating our Arc for struct I will zoom in here a little bit not that much temporarily so we can have both on the same page um so if we look through this what do we [Music] need we need an 32bit or we need an 8bit INT which will go go from 0 to 255 we will need a an array called s which will be consisted of 8 bit values and 256 of them then we have the J value same as I one in8 and then we have the [Music] key and that’s basically it so let’s summarize we [Music] need int uh I in 8 I J and later on we will need a k so I’ll put it here and then we will need the array so in 8 s and 256 of them so we have I with J we have the K and we have the S do we need anything more down here we need temporary variables as well but then I won’t put them in the struct so okay this is this is all we need for our own structure so let’s begin writing on our let’s begin writing on our initialization function and this will let’s copy this whole thing let’s include our let’s include our Arc 4. h there’s something weird going on with the Caps look include r4h I wonder if you can disable the caps lock I never use it anyway I use shift okay let’s see include AR for. H and then we will do the visualization function so it will return an arc for structure pointer and the first argument is the key the second is the size of the key like so and the first thing we need to do is allocate space for the uh for the actual structure so I will create um point a point pointer for that I’ll just call it P because we’re going to reference it quite a lot and P should be equal to Malo and it should be the size of stct s AR for so the size our stct that many bytes of memory we shall we shall allocate and here I will do an if clause [Music] so let me just check the return values for my Look Man 2 No Man 3 Meo so I know it Returns the memory address but if it fails [Music] return [Music] value they return null and they set arome okay so let’s just do something like a ser insert P [Applause] error I remember then it will check if this has errored out and if so display an error message and quit because if you can’t allocate memory for our structure there’s no point in continuing show okay so now that we have allocated our structure now I will just do this and I will work in the following manner let’s close this down and change up the size a little bit and then I will paste this in and make block comments out of it I think it’s command this or control this let’s do something like this instead oh annoying I never seem to learn vs code for Mac I know all of these different things on my PC but it’s not the same on my Mac well well this works too okay so now I have in the comments what needs to be done and then I will just do it but before we begin I want to zero out all the state variables so let’s do something like no let’s just do a simple simple thing in eight X and 4 x = z x less than 256 x++ and we want to take the PS so that is the this array I want to zero that out so PS of x equals zero and then I’ll just do p i equals P J equals p k equal zero I like starting from zero instead of random randomness okay so the first thing is this Loop right here we will iterate through 0 to 255 with this I variable and we will set s of I to I pretty simple stuff the code will look kind of difficult though but it really isn’t why is this not oh never mind okay so for p i = z and p i less than 256 p i++ and p s of I equals I okay this is done so if we do one thing at a time it’s quite simple to do this actually can’t say that for every crypto and then we will set J to zero but we have done that already so we will jump into this Loop and we will let the the I variable do another uh ENT identical for Loop so let’s just copy this line like this and what will happen then we need to Temporary variables as well by the way so we need int 8 I will call them temp one and temp two and I want to zero them as well from the beginning so let’s just do temp one equals tempure = z like so okay so what will happen inside of this Loop let’s remove the things we have done already okay so this is a rather difficult line I want to break them down so what’s the first thing that happens right here well the parenthesis is evaluated first so let’s set let me see key I mod key actually let’s evaluate this first I mode key length so temp one will be equal to key so it will be key of I key of I no where am I we are here right so I mode key length so p Arrow I modulus key length so that’s the size okay so this part is okay now we can take the rest of this parentheses one at a time so P J [Music] no temp 2 = PJ plus p s of I plus key of and then the stuff we evaluated right here so key temp one and then we will set P J so now we are doing this part so PJ should be equal to everything in this parentheses which was temp two and mod 256 modulus 256 like this and finally we should swap the values of s of I and S of J so let’s set temp one to p s of I no not just I we need to change those occurrences to [Music] Pi and p i there’s a lot that can go wrong here as you can see you need to be very precise so Temp and that is why I I could do everything in one line if I wanted to but it’s very error prone and that’s why I break it down with these temporary variables so temp one is equal to p ps pi and temp 2 is equal to PS PJ and then we will just swap them so [Music] p s of p i equals and here we see that temp 2 equals this no temp one equals this that I’m working with now which means it should be equal to Temp 2 instead and then we have PS of [Music] PJ which is currently equal to which is currently equal to Temp 2 and it should be equal to Temp one and that’s it the code is very difficult to read but it’s quite simple and it’s quite easy to follow it step by step if you break it down into smaller steps and that is basically it I’m going to do one more thing though because if we go back to the Wikipedia page and we go to the next step we see that they zero out IJ and then they have an endless loop which happens every time you encrypt a character so we have a function which encrypts a character which means we only have to worry about this but this part we should put here in the initialization function because then we can just do several consecutive calls to our Arc for bite function so P of I equals P of J equals zero like so and then we just return P I think we did it right if we go back here and we remove this line and put this line back then we can print instead of printing the key let’s print [Music] let’s print Arc for S so the initial state of [Music] the the initial state of the encryption engine and I will put a one of these on top as well so we may see the difference no sorry can’t do that we haven’t initialized it yet but okay let’s see what happens clear jump down a bit make clean and make okay couple of Errors if we go to the very beginning warning suggest parentheses around assignment used as truth value well I want to use it as a truth value I I don’t really care for warnings like this I I if I want to code it this way I will code it that way implicit Declaration of function assert P error okay and here I forgot got something and Arc for has no member named s okay so a couple of more small typos uh if we begin in the H file I guess this is the problem is this a big S or small s it is a small s so why doesn’t it remember called s did I perhaps Arc for p that’s weird maybe it’s something because of this we should check if x is less than 256 so that was an easy one and what else assert peror where is that Lo okay at the Man 3 assert [Music] P okay I need this G Source [Music] thingy let’s try it again rank clear jump down a bit clear and make boom okay in 8 i j k unknown type name unknown type name in8 uh I put this before these let’s move them so I don’t like you have to break this up but what can you do this this just a warning error I UND declared okay I missed one line [Music] 18 WR 8 so this should be p i and this should also be p i okay what no error Arc for Undeclared now the problem must be higher than that Arc for Undeclared in example and pointer Targets in passing Arc for init key sh star that’s weird didn’t I use my in 8 for that function declaration let’s check it out so in8 [Music] key and in8 S let’s put this back right away [Music] and okay it’s this function in 8 [Music] inut 16 well where is it let’s check it out again so expected [Music] in8 Arc for a nit key pointer Targets in passing argument one of AR for in it differ in sness because this is a char inate [Music] key so key is a [Music] Char okay let’s type cast it [Music] down where do we have it’s right here okay so it’s currently a let’s see it should be an in 8 so okay let’s see what we have still a warning about this one but that’s nothing we can do anything about un reference to Arc for init uh we need to link that [Music] one let’s just no so go into the make file and then we will do let’s make it easy I will just do uh Arc for.so as one of the input arguments so clear jump down a bit make and now it still doesn’t compile undefined reference to Arc for init what did it draw GCC AR 4.so [Music] do do I include it in the header file include Arc for. H include Arc for. H Arc for init and if find reference okay for the time being let’s cheat a little bit I will fix this later around I don’t have the patience right now so I’m going to go [Music] and when we compile final program we do AR for. instead like so okay this time it worked we probably need to explicitly export uh the functions when we use the the share Library I will dig into that in a little bit but now we do have ourselves a binary so let’s try it out that doesn’t look very good let’s do M TR DF M look I don’t know look let’s try the S right initializing encryption H how did I write that if Clause by the way maybe I reverse the conditions let’s see if be my look okay this should [Music] be the other way around so if P all right make clean clear and we run example did it remove everything when I did make clean Arc for CH HC yes so how come it freezes there Malo size of struct s AR four if that is zero assert P error for X = 0 x less than oh 256 I think that zero means that it’s some weird number format okay no errors at all no warnings even but the same outcome what is this do we have an endless loop on our hands that’s probably the only possible thing right so p i = z while Pi I is less than 256 maybe we should do this with a little bit bigger structure um this could be in6 since then we are probably overflowing that 8bit variable so that was is n the case 4 x = z and what is X x is also an in8 so that should be the same problem though right there we go finally okay so this is part of the internal state of the of the encryption okay so the next thing we need to do that is creating the arc for bite function which will create one single bite of the key stream and the key stream is what we will use to encrypt and to decrypt stuff so let’s begin I will have in 16s with temp one and temp two just like before and we do need an argument by the way we need to attach the the structure so let’s alter this and put in the arc for Star so we can have access to the internal state of the encryption and just like before I will go to the Wikipedia page and this time I will copy this part so in this code studo code right here they use a wi Loop and they loop as long as it’s generating output but will not do it like that instead this function will be called each time we will produce one bite so we don’t need this Loop that will be handled in the encryption function so let’s do it like before and take one line at a time so we will do p i [Music] equals and then p i + + one and we mode it with 256 first one is done then we do similar with the J part so PJ equals PJ plus PS of p i so we just replace the variables with our variables inside of the structure and we mode this with two five6 just like before okay then we will swap the values so this is like we did previously with the um the initialization function so I will let temp one equal p s of p i and temp 2 will equal PS of P J like so and then I will just I missed the S right here and then I will just do PS of p i equals something and PS of P J of p i PS of PJ equals something okay so temp 2 equals the J part which means it should equal the I part now this equals temp 2 and the PJ should equal temp like this and then this one is done as well why did it mess up the indentation never mind okay and then we have this T variable that is their version of our temporary variables so we’ll just continue as before so temp one equals in the parentheses p s of p i so this is not really a spectator SP Sport I hope you don’t find this too boring but we’re almost done plus [Music] p s of [Music] P J and then we mode it with two 5 six and then we use the K variable for the first time so p. k equals p s of ter one and this is the first final output bite as we can see right here so let’s take care of these indentations and then at the end we just return PK like this and then we have our Arc for by function which is the most important in this entire project so so the next step will be to implement the arc for encrypt and this is quite straightforward to do now that we have a um Arc for bite function so let’s see we need one more argument we need to include the Arc for structure so AR or do we yes we do Arc for star and we go here and do Arc for p and in 8 this will be the what shall we call it the thing we need to encrypt the clear text let’s call it CT for Clear text and in 16 this is the size size of the clear text that we want to create and we’ll return this as a um well as a Char buffer a regular string actually so let’s create a in6 which will hold the amount of memory we need to allocate so let’s call this mem size and we will need exactly as much memory as this size + one okay so we don’t really need to because when you encrypt something if we encrypt ABC the resulting Cipher text will be something like this it will be the same number of characters which makes it quite convenient for us we don’t need this variable instead we’ll just do um let’s create a variable first so let’s call this cyer text and let’s call this clear text because both will abbreviate to CT and we can’t mix those so in8 Cipher text and Cipher text will be equal to8 look and we [Music] want size + one size should be enough really but I like allocating one more just in case we will also need something we can use as a counter let’s call this in 16 x we do a for Loop where we set X = to [Music] Zero and we’re going to loop as long as X is less than the size and x++ and what are we going to do at each iteration let’s create a let me see we need this and that okay let’s do it like this so the cipher text of X will be equal to the clear text of X and then we take this symbol and some people usually mix this up with the power of but this little symbol in c means exor so exor is a binary function like do you have if you have two zeros the result will be zero if you have one one Z and one one and a one the result will be one if you have a z and a one so the other way around it will also be one and finally if you have two zeros it will be zero so that is what xor is it’s usually used in conjunction with uh the key stream that a stream Cipher like Ark for produces so here we will just call Arc for bite with our p and that will return one BTE of key stream which we will exert with a clear textt and that will produce the cipher text and let’s do a an error check here as well so if Cipher text is zero then we want to um [Music] assert P error R number like so and if everything goes well we will simply return our new buffer Cipher text quite simple straightforward encryption function and we need a decryption as well but that we have already defined because it’s the same function just that we give it the the cipher text instead of the clear text and the key is the same so basically this part is the same okay so that is done as well and before I forget let’s see encrypted equals R [Music] for so we can take this back now and we encrypt the de clear text and we print out the the encrypted Sor this should be the size of the text this should be the encrypted because this time we don’t want to check the S variable in the structure we want to see the actual encrypted text yes okay so after we have printed the text what do we do do we just use the decryption function no we can’t do that because in order for everything to be the same we must uninitialize the uh the arc for and we need to reinitialize it with the key again so we start everything from scratch and then we can start to decrypt otherwise it won’t work so let’s create [Music] our uninit function as well and that can be avoid Arc for let’s make it easy for us for the time being because there’s only one thing we need to do at the moment when we when we uninitialize and that is to free the um memory allocation so let’s Define arc for un liit of X as fre X I will also need to find let me just do a fast Googling after export C shared Library function because there’s a special string we need to use to export the functions let’s [Music] see this one so let’s make a definition we Define a keyword named export and it will be the same as this so all the functions that we want to export like the arc forb function we don’t need to export that because the end user will only use the encrypt and decrypt functions and the init so we put export before this and before this say and we need to do the same here so export and not this one but this one export like so okay so that that is done as well now we may continue our example so we have printed the the encrypted strings now we’re going to uninitialize so we do Arc for un init on the ark for pointer then we repeat some of the steps like before so let’s copy this part there we go [Music] go and let’s create another one of these CED so I will copy this part for okay something like this and let’s put the arrow one two one two like this instead okay so we initialize [Music] and we need to change the order of these because we need to decrypt this first so it’s initialized now we will create our decrypted so decrypted equals and we will use the decrypt function but but as you know it’s the same the only thing we’re going to change is the from here we have the cleare text before now we will do the cipher text which we get from this encrypted call so where were we decrypted equals and this should be encrypted and everything else is the same and this should be decrypted as [Music] well and then we don’t need to print the binary okay so if we have done everything correct then [Music] the encrypted the decrypted text should be the exactly the same as what we had from the beginning so we take the text we encrypt it and we decrypt it back to the start so let’s see okay let’s save and we make clean jump down we clear and we do make okay not a lot of errors and warnings let’s start from the beginning error T undefined size plus T text 54 in Arc for. [Music] C 54 Cypher text size + t + 1 should be plus one okay we got more errors let’s do make clean first make okay warning this four clause does not guard 4 x = z while X is less than size x ++ x = z x is less than size X ++ which shouldn’t be a problem this St doesn’t guard this statement return CER but the ladder is misleadingly indented okay so it even checks my indentation thing but sometimes that’s good actually I have corrected errors in the past because of that so let’s see what it [Music] says okay it’s this part let’s move it here we make clean we go down and we clear and we make again okay passing argument one of Crypt from incompatible pointer type Arc for encrypt from okay let’s see Arc for encrypt from encrypted equals Arc for encrypt from and from is set to this okay we probably need to type cast this down but it worked before right never mind in int 8 star let’s do it like that do we have any more occurrences so the same decrypted no okay let’s try again make clean and make all for encrypt from incompatible pointer type encrypted equals uh wait a second I forgot to attach the structure right we did change the signature of that function so where were we look cryp the first argument should be the arc for like this and same with the decrypt so Arc 4 and we need to add a variable to the macro as well so XY [Music] Z XY Z like so let’s try again make clean clear and we make and we have this sness problem again so encrypted equals AR for encrypt AR for encryp so let’s see encrypted how did we declare encrypted okay let’s move this to its own instead decrypted decrypted as well I think so in eight encrypted decrypted we make clean and we clear and we make okay almost there another okay that’s our temporary assignment we don’t even need that anymore so let’s just remove this part and this as well save make clean clear and we make okay it compiled let’s see what happens okay initializing encryption done and then then it shows the string that we want to encrypt and it shows the hexad desmal version of the encrypted text then we reinitialize we feed it with the cipher text and we end up with the same string as we had from the beginning so everything works the only thing we should add to this that is the remember when I talked about the that some people think that the arc for encryption is not safe one of the biggest concerns was that the first like thousands of or millions of uh bites is um not good enough so to speak so we need when we initialize we need to like I call it to White Wash we need to whitewash away the first like 50 or 500 million [Music] um of these yeah so let’s go into our encryption function no our initialization function this one and I want to create an M32 which I’m going to use as a well I’m going to use it for a for Loop basically I don’t really want to call it I because that makes it interchangeable with this Pi so let’s just call this C for count n for number and is good and let’s go into the let’s see Arc for and we create a macro for this so we Define arc for white wash and we need a we don’t need an argument actually and what we’re going to do if by the way we do need an argument let’s take the variable for the loop as an argument so the only thing this will do is a for Loop where we go from X = Z while X is less than um let’s call it white wash Cod or what was let’s call it m so this these are millions of iterations so X is less than Ms * 1 1 2 3 1 2 3 and i++ and the only thing we need to do is okay we need one argument more the only thing we’re going to do let’s do it on the next slide uh we will call Arc for B f with the structure or pointer of the structure as an argument so basically that we will call this which it will generate a a bite and each time it Loops it will do that but we’re not going to do anything with that bite because all we need to do is get it had in the well in the state so to speak but if we do it like this then GCC will recognize that it’s redundant and it will as part of the optimization it will just remove this so we will need to typ cast this to something called volatile in8 like so and that basically means in this context that GCC should not uh optimize it okay so let’s put this as part of our initialization so when we are done with the rest of the initialization steps at the end here we will simply call The Ark for white wash and specify our variable for the iterations and the name of our structure which is p like this okay and if this works we should see that it takes uh longer when we run this initialization a couple of seconds uh we also need to define the M’s so how many million iterations should we have and I want five 100 million think that ought to do it if you think it takes too long when you run this try changing this to 250 or 100 because I have a quite fast CPU so this should go quite fast and we save everything and hopefully we haven’t introduced any additional errors make clean and we clear and we make yes we did okay what does it say okay i++ that’s [Music] wrong where were we here so it should say x++ right all right let’s try it again clean down bit and we clear and we make it compile let’s run it initializing and as you can see it takes a couple of steps and then it does the same as it did before only this time it’s probably safe as long as we have a really good uh encryption key which we don’t at the moment at the moment we only have in this example at least we only have the the word Tomatoes we should randomize a 20 48 bits key if we were to use this in the wild but everything works exactly as we intended it to so we have successfully implemented the arc for uh crypto and we have turned it into our own our very own uh Library which can be shared between different applications and when I create um a project for transferring and encrypting files I will use this library for that so then I will show you how to how to use this like library in your code but I hope you enjoyed this and don’t forget to subscribe if you like this and want to see more there is a lot of uh Advanced to see videos coming forward so don’t miss out and stay tuned thanks for watching and thanks for today [Music] the first thing I would want to do before we start with actual encryption tool is we need to install the uh the library so how do we install our own Library well let’s go into our uh directory and let’s alter our make file a little bit so if you remember the ultimate Target of this make file is to create this Arc for.so however I’m going to rename it to lib Arc for so because it will be easier to uh use it if it has the correct naming standard I will also have to check what the correct Library directory is before it was always user lib but now at least on my 64bit Linux system it is this one so you need to add this x86 Etc so let’s grab this and um we also need the include directory but that’s just user include as usual I think us include yeah so let’s create two variables one which is going to be the ink deer and I will put user include that’s where we put the H files and then lib D that’s where we put the library file so when we have compiled lib Arc for.so then we will copy lib Arc for.so to the let’s see the uh lib deer and we’re going to copy The Arc for. to our ink there like so and then we’re going to run the command LD config which will update all the configuration files necessary for the library to work okay let’s try it and we need to run this as rout because we don’t have right permission to that directory so let’s begin by doing make clean and okay by the way it will be better if we create a new Target which we’ll call install and let’s grab these three lines and put them here instead so in this Arc for we compile the actual library and then we do make install as its own command to install it uh so make clean let me just clear so make clean and then make and finally Soo make install okay no errors so let’s go to the directory for today’s program I’m going to call it um f see and I’m not going to tell what the fs stands for but the E stands for encrypt and that’s because I don’t want to spoil what the ultimate end with this project is and I’m going to tell that in a later episode so let’s create a test file test. C and we will include just the standard iio and we’re going to [Music] include we going to include our own arc for. H and we use these angle brackets because now it is installed globally on the system and then I’m going to just create an empty main which return zero so basically I just want to see if it compiles um okay we need to let let’s run one of the functions in that Library so what do we have we have AR let me just let check so more youer include AR four [Music] so let’s do Arc for init it takes [Music] the the key and the size of the key that’s right so Arc no Arc for init and a key and the size of the key invitees so five this should work and let’s cast this to a volatile so let’s cast this to volatile uh Arc for pointer and that’s basically just so the compiler won’t simply ignore this line because we don’t do anything with return value okay so then then we first compile it with the dash C so test. C and we get the object file and now when we’re going to link we do GCC test. o o text and we uh if we don’t add anything else we get the error that it doesn’t find Arc for in it but this is globally installed on the system so all we need to do is add- L Arc 4 and it compiles and run great so so now we have installed our uh Library okay guys uh let’s end there for today and we will continue this uh project uh another day don’t forget to like And subscribe and thanks for watching and thanks for today sup guys welcome to Today’s Show today we are going to answer this question y 755 you have probably sometime used the command change modk 755 and the name of a file or directory but what does this 755 mean in the detail this and more we’re going to talk about today when we are discussing Linux file system [Music] security and this topic will be divided into the following different things we are going to talk about file permissions uh and that also is applicative to uh directories uh and it’s a huge part of the Linux and Unix security we will also discuss the different targets that you can set these permissions for and uh we will also discuss the change mode command in detail how to use it and if we have time left I will also mention the change own uh command plus I will be teaching how to view permissions as well so let’s start with the different permissions that are available on a Unix and Linux system so first and foremost we have read and read is what it sounds like if you have the read permission on the file you can open the file and read its file contents if you have read permission on a directory you may list the contents of that directory all the file names so read has the character flag of R and that is important when it comes to the configuring of permissions using the change mod command and also while viewing the permissions but there is also a numeric representation of that uh R flag so for the read permission that is number four and there is also a binary representation but I’ll get back to that in a little while then we have the right permissions and that is a w as a flag and number two in the numeric representation so what is the right permission well if you have the right permissions on a file you may edit the file alter the file contents and save the file you may also delete the file and uh if you have the right permission on a directory you can do basically anything almost you may uh delete files you may create files rename files but there is also a third very important permission which is called AIS and that has an X in the flag representation and a number one in the numeric representation so what does access mean read and write permissions are quite similar for directories and for files but access differs quite a lot so if you have the access permission for a directory you may enter that directory you may access the directory so basically it means you can CD into the directory uh if you only have the access and not the read you may not do LS and show the contents of that directory but you may access it and you may go to sub folders if you know the name of them and if you have the access permission on a file on the other hand that means that you may execute that file so executing a file that’s basically when you run a script or when you start a program so for example the LS command is a program if you have the X flag you can you may run the ls command otherwise you will get a error message saying permission denied so that is basically it when it comes to permissions but I also want to talk a little bit about their binary representation so let me just scroll a little bit okay so why are we talking about binary that is because I want you to understand how this system is constructed it’s a very very intelligent system which are based on those flags so this kind of flag system is not only used for permissions it’s used for a lot of different things in the Linux operating system but also in a lot of lowlevel code like C programming and stuff and you will soon understand why okay so if we convert the number uh one to Binary with four digits we will get 0 0 0 1 okay if we convert the two we will get 0 0 1 0 and notice that we don’t have a three we have a one we have a two and we have a four why is that well if we convert the four to Binary then we get 0 1 0 0 so a pattern emerges what we can do is we dra draw a line right here and right here and then we see that all those ones are in different columns uh which means that we can combine them as we would like so let’s say we we want to combine the read and the write permission that would be the number four plus the number two = 6 so if we give the number six when we configure uh the permissions it will set both these two flags and if uh you use the ls command to check the permissions then it only needs this six because if you look at these three numbers 1 2 and four the only way to produce a six is by using the four and the two and that is true for all possible combinations of these values as we can see here the ones are in their own column so if we set this or if we set this or this it won’t alter these ones and what is it that mean well it means that with one single integer we can basically store as many flags as we would like at least up to 4.3 billion or whatever and we can store all possible combinations of these flags as well in one single integer and that is a very very powerful way of storing data okay the next thing we’re going to talk about is the targets and the output of the ls command and let’s start by talking a little bit about the targets because we have these permissions read write access but who do we give the permissions what do we set it on well we have for every file and every directory we have three different Alternatives we have the owner and that is also called the user we have something that is called group and we have other and these are kind of self-explanatory the user or the owner that is the owner of the file basically so if you have created a file in your home directory for example then you are the user or the owner and uh that means that you’re allowed to change the permissions if remove all the permissions then you cannot open the file but you may give yourself read write access and then open the file can also delete the file and stuff like that so for you you need to decide for every file in every directory if the owner should have read or write or access or any combination of the three and same goes along for this group so every user on a Linux system is a member of at least one group but possibly several so basically the administrator the root on the system May create the those uh groups and you can be a part of one group or you can be a part of uh thousands and you can be part of named groups or simply a numeric representation if you set permissions for a specific group then you have endless possibilities because if you just have these three different levels the owner the group and other other is just applicative to those who are not the owner and not the member of any group so it’s a very simple uh system with small building blocks but you can create really powerful things with it and we are going to talk a little bit about the flags of these targets as well so let me just put them down here again so the user is the official name for this owner of the file so I will call it user from now on but sometimes it it’s being called the owner as well and then then we have group and we have other so it’s very easy to remember those flags because the user has a u the group has a g and the other has an o so when you set the permissions you have the possibility of using these Flags to specify the target but there is also a combination of all these which is the a flag and that basically stands for all so it Alters all these three targets and sets the permiss permissions you specify okay what else well you may also use combinations of these so if you want to set for the user and the group you just do U or other group OG so AC a system but kind of simple to use anyway uh another thing I’m going to do is I’m going to color these different uh targets so the user will be yellow in this example the group will be green and the other will be purple or possibly pink and and then I’m going to zoom out a little bit so we may see everything here okay so if you do the regular LS command then you will uh only see the names of the file by default unless you have changed the default settings by an alias or similar but if you do like it’s shown here ls- A L and this is an L A small L not one so ls- a then you get one line per file or direct directory and you get some additional information like the day it was altered and the the the size of the file uh and stuff like that and then we have the names to the right but the thing that is interesting in this example are these right here so perhaps you have seen this before but haven’t given it much thought these are the different permissions and it might if you look if if you’re not familiar with this it might be difficult to make sense of this because it’s just a lot of different characters and you may not see any pattern here but let me do this if I take my Jello pencil and I highlight this part and I’ll take my green and I’ll highlight this and finally I will take my purple or pink and highlight this and then I will zoom out a little bit again do you see now so in this example if we look at the first uh the first uh file or directory the ETC then in yellow we see the users permissions that’s always displayed first so the user has read right access and uh the next one is the group and as you can see there is read and there is access but there’s only a dash in the place of the right so this means read access but not right and same for the other at the end here and if we look at the next line there is the same uh format but this time there is read write for the user and read for the other two then additionally we have this lone lonely d right here uh and that only means that this is a directory and often you will uh be able to identify that because there’s a either a zero on the size or a or the same number for every directory plus you can see this slash at the end in some implementations and configurations of the ls command okay and about targets now we’re coming to the last part of this uh episode change mode change mode is the command for altering permissions on a Unix and Linux system and you do change mode and then something and then the file name like test.txt but what do you type in the middle right here well let’s say we want to give those permissions for the files that we see right here so read write for the owner and read for the other two then we have uh a couple of options we may construct a string which looks like this U equals read write group other equals read so if you put this string in the middle here then you will get those permissions that’s one way another way is to give all the read permission and then the user will add the right permission so this is a plus u+ W so there is the a lot of possible ways to define those groups if you just do if you leave out the A and the U Etc and just do plus read right then it applies to all three groups and you can also do a equals nothing to remove all the permissions I do that sometimes so I run this command and then I specify like group plus r or something like this okay that is one way which is good to use when you are setting permissions that is not very common but if you are changing similar permissions like often there are there is an easier way and that is using numbers so now we come to this 7 five five stuff what does 755 mean well the first number is user this is the group and this is other and if we go back to the first is slide right here if we combine the four and the two and the one then we get a seven which means that seven is read right Axis and the five well there’s only one way to construct the five and that is one and four of course so read and access that is five so this command means that the user will have read write group other will have no the user will have read write access and the group and other will have read and access that’s correct so 755 is something you use a lot because you want to give access to directories and er run permissions for scripts and uh programs and another one which is very common is the 644 that means us sir read right group other read that is usually what a regular file will have will have by default the directories most commonly have the 755 by default and finally another number which I use often on home directories is 700 which means I am the only one with any permissions to even access my home directory what have we learned to today you have learned about Linux file system security that there are three parts to it the file permissions targets and the change mode command let me say a couple of words about the change own by the way as you might have guessed the change own command changes the owner of a specific file so let’s say there is a user called user 5 and you want to give them the ownership of a directory then you do change own us Sur five and then the directory like Etc or whatever if if you want to give a specific group as well then you add a colon and then you type the name of the group so if you have a group called users you will type user five colon users today you have also learned about the read and write and access permissions and uh they flag and numeric and binary representation and what how you can make use of all of these combine them in infinite ways you have learned how to use the ls command to check the permissions and what these different characters mean you have also learned about the three targets the user the group and the other which uh you are able to set permissions for for any file or directory in the system and finally you have learned the change mod and the change own commands which changes the file and directory permissions and the owner respectively okay guys this was a new format using my I P to draw those things I think this is a good format for these kind of videos uh let me know what you think in the comments and uh more c videos are coming up so please subscribe by clicking the little little red button on the bottom right on your screen if you want to Subs subscribe and uh thanks for watching and thanks for today okay so how will our file uh encryptor work well we’re going to create an out file which consists of the first two bytes is a random number between 1 and 65,536 then we will have some padding so if we have the random number 500 then 500 bytes of random bites will follow then we have a 100 a 256bit hash value which will be our hashed uh password or or hashed encryption key that’s so we have an ability to check if we have supplied the correct password or not and then after that all the contents of the file and all of this will also be encrypted using the same key as is hidden in the Sha hash and if you want to know how this works and why I need to do all of this and I have recorded a special episode just for that which I will also link to in the description okay so let’s start [Music] coding as usual I’m going to start by defining the main so I know what functions I need and where when to do them Etc and then I will start filling out the those empty shells with real functions I call it a function signature driven software design okay so let’s include SD IO and all the other ones that I let’s put that in the H by the way so we’ll simply include FS e do H and inside of here we I will put all my regular include files perhaps we won’t be needing all of them and then we can remove them later on but this way we don’t need to pause all the time by looking at and finding these include files string.h and finally we also need our very own arc for. H and let’s create a sign signature for our main in and Char double star like so so how do we want to structure this well we’re obvious is obviously going to need a an arc for instance and we are going to need a key an in file and an out file so sh or let’s use our our own integers so int [Music] 8 let’s make it easy we can convert to our own when we need it so Char and what did I [Music] need in file and out f and we’re also going to need an INF FD and an out FD so that’s a file descriptor that we get from the open Cisco and we’re going to need an int8 for our [Music] key and then we need a couple of sizes at least we need the size of the key so let’s do an in 16 key size like that okay so if r c is less than how many do we need one two is less than three then we’re going to print to standard error and tell that the usage of our binary file is in out and the first is arv and that’s all there we go I hope it the text size isn’t too too small for you and then we’re simply going to return mine as well and now that we have enough arguments we can assign our in file to rv1 and now out file to RV two little bit easier to handle so we don’t have to remember which these are next step is asking for the key or or let’s open the file in file first because because we want to abor early if we don’t if we’re not able to do that so in FD equals open and we’re going to supply the INF file and we’re going to do read [Music] only like this and if infile is less than one F print f stt unable to no let’s not let’s just do print error open and return minus one okay so now the in file is open let’s do the same with the out file by the way so out FD equals open because the file may already exist with the wrong permissions or be badly formatted Etc so let’s open both out file and this is O right only and we also need all create so we create uh the file if it’s not there already and we also need permissions for the file and that’ll be 0 0 600 so only our user will be able to read and write that file and if this open operation fails then FD will be the less than one and in that case we want to close our [Music] NFD and then we’ll do the same as before let this okay so now both our files are open let’s read the key so [Music] key Let’s see we need to have a function which reads both the key and the size of the key right but since we are reading the input from the keyboard we can just do a string length on it we need to improve this when we do our much more secure version in the future sometime okay so key equals read key and uh maybe we’ll Supply some kind of a [Music] prompt key like so and in this case I will do an insert so we also need to include all the sech stuff and that is basically two things we need to [Music] include insert. H and we need to Define G Source if we don’t Define the new source course the assert uh function will still work but another function which is assert P error will not but if we have that definition at the top of our H file everything will work perfectly fine okay let’s see in 6 no the it should be an int8 pointer which we called read key [Music] and in8 here as [Music] well so we need to basically read the key from the keyboard and um uh don’t Echo the characters to the screen so let’s see we’ll wait a little bit with that we’re going to set our what did we call the [Music] key key size key size will be equal to the int [Music] 16 of string length key well let’s do Char like so and then we can change our key to in8 okay so we have read the key next step is to start reading from the uh standard no the next thing is to start writing to the file and the first thing is those two byes of the padding length which will be completely random using a secure Rand function so we need that secure Rand function so let [Music] us let’s create an in8 Let’s see we need to have let’s do in6 and we will call it [Music] the padding length pad size and the actual padding will be stored inside of that in 16 right yes and we need an INT 8 array for the um actual padding bites like so so basically we will do something like pad size or pad size equals [Music] secure round and we need two btes something like that P size [Music] I’m not sure if that’s the best way though it’s a little tricky to store these kinds of data well how do we store it because we’re going to need it for an in6 like this but also for a long string of characters I think we’ll do two different variables this must be the easiest way so let’s say we have an INT 16 called pad size 16 and we also have an INT 8 which is the pad size [Music] eight that should be it so pad size 8 will be equal to this and pad size 16 will be able will be equal to let’s see we need pad size eight D referenced so let’s have um it’s a lot of variables for the same thing this can probably be done much better but I don’t care right now I just need something that works works so pad SI 16 equals the in 16 version of pad size 8 and the actual pad size will be pad size 16 the referenced that should be it right think we need to print this out to see if it really works P size perent [Music] d and this will be the in of pad size this is a lot of different conversions well let’s see if that works um right okay so the only thing is we have the opening of files this is commented out and then we have this so then we can start with this a secure run thing yeah let’s do that close [Music] NFD close alt FD free pad size eight return zero like so okay so how do we create a secure a cryptographically secure function for generating random random numbers there is actually a system call which is [Music] called if we go into the U random I think there should be yeah get random and that is a system Co so basically it returns the size of a buffer of a specific size so if we say that we need eight bytes of random data we get that perhaps or we get less that depends on the entropy pool so basically the the this function uses a lot of different signals like what has occurred since the computer booted up all of different things it puts in a a big pool which is called the Anri pool so you can only create a finite uh amount of these random bites between all all the the whole system and when you run out of entropy you have we just have to wait so you can call this function with two different flags first we’re going to call it with give us all that you have and exit if you don’t have enough and uh if we don’t get all the BS then we will call it again but we will put a message to the user that this may take longer than usual and then we’ll call it without flag well the alternative is that we don’t use a cryptographically a secure version of this and I want it to be un Hackle so this is the stuff we’re going to use this random which means that it doesn’t use a pseudo random function which is not good enough for cryptography so we need to supply the random and then it relies on the ENT trippy pool and basically we will let it be nonblock the first time around and uh the second time without the non block is says Pi so uh size return value and we have the buff and the [Music] size and I think we can supply a Nole buffer to get it on the Heap or perhaps not never mind let’s allocate that ourselves and where is this CIS random. so let’s go into our H file and include sis random. and let’s see this will return in 8 array and we called it secure round and we just need to send number of bytes let’s do in 16 and let’s create this function so int8 array and secure round we will have an n16 size and we need to have an in8 pointer let’s start by checking the size length so we need to assert that size is bigger [Music] than zero [Music] and yeah that’s basically it P will be equal to and in 8 my of size byes we will assert [Music] P or by the way let’s not assert P if yeah let’s a SE p if we run out of memory so Malu will start to fail everything will fail anyway so okay so now we have our buffer we need something that catches the return [Music] value size [Music] and will be equal to get Rand get random and it will be P perhaps we need to no we probably don’t need to type test that and and then the number of bites that size maybe we need to type cast this to a size T and we need the flags right so this and then we have the same but non block so we need it to be random and we need to be non blow so this may return let’s do if n equals size then everything is okay and we can return p and if n is less than zero something has gone wrong and we need to return zero else it means that we did not get enough bytes which means we have to run this again so we do F print F STD L warning pool is empty this may take longer than usual something like that and then we call it again n equal get random and this time we need to Incas incase pointer p+ = n so we will supply p and this time this value will be size minus the N bytes that we have already gotten right and we need to supply the gr R [Music] ND uh random but not non block there we go and if n equals sides [Music] return we need to D allocate by the way and yeah then we need to save a copy we can’t free it if we have jumped it around well we can just jump it back that’s better actually no we don’t need no how many B okay let’s do it this way no hesitation so if n equals size then we return start if n is less than zero then we will free start and return zero and in all other cases it has failed again so we can simply do else here instead and this should be our function so if we call it with two bytes like this and everything is okay we should get different result each time let’s see if this even compiles nope but when does it ever first time in main second argument of main should be sh star star what did I do ah forgot one star we can’t make the main a single star there we go one G couple more to go right open did you mean pop po p open no I did not me me P open that’s a library called for nbes let’s see open what do we need man two open what do we need Okay so let’s include this FC and whatever if INF file is less than one comparison between pointer and integer in file uh where is it if in file if in [Music] FD in [Music] FD alt FD this one was right inate padding unus us variable key size set but not used warning unused variable but it’s compiled so let’s see what happens [Music] F yeah we need to mock these files let’s just touch in file and let’s do FC in file out file 45 938 40 950 yeah this works perfectly well great okay guys let’s create the read key function which will be a quite simple function it’s going to read the key from the keyboard and uh the only thing we have to make sure is that we don’t Echo the characters to the screen so the only thing we’re going to have right here is a prompt and what do we need we need a buffer represented by a pointer so so let’s see we’re going to return an int8 so let’s make this an int8 pointer and we’re going to Let’s see we need a temporary buffer on the stack because we don’t really know how many characters to allocate so let’s let’s say let’s do unsigned Char no let’s do Char and let’s say we have a Max limit of 20 48 bytes or that’s a bit much perhaps because the biggest size uh in a 24 the 8bit encryption system is 256 okay so let’s make it 25 five no 256 because as you know this isn’t the index this is the number of um chars that we want to allocate so counting the zero it’s 256 okay so let’s begin by write writing the naive version of it that Echoes to the screen and then we will simply uh fix that after words so how do we do with this we don’t have to make it so difficult let’s just begin mem setting shouldn’t call this AR buff we’re going to M set the buffer with 0 256 of those then we are going to to read from standard in standard out standard from standard input into our buffer and we have to no we don’t have to cast that and we’re going to read a maximum of 255 so we have room for the ending zero as well okay so now we have read one line we need to remove the ending new line from the input as well and we’re going to need an in for our Let’s do let’s do an in32 for our length know why should we do as big as that an in h right so size and we’ll simply just call string length on the input and then we will let’s see if we have AB b c d that’s the length of four and the indices will be 0 1 2 three and if we have a new line at the end this would be index 4 and the size will be five so let’s do an index as well and index will be the size minus one so let’s do let’s Point our pointer towards uh buff plus uh index and let’s zero that out like [Music] so and then we will allocate our buffer so this will be an in Mal size and if my look fails everything will [Music] fail and if it works we will simply copy our [Music] string to p and from buff and the size will [Music] be size right or maybe minus one by the way just to make room for everything um okay let’s remove this and did I forget anything yes we need to type cast a little bit so the size is an in8 so we need to make this in8 no right an in8 like this and we need to send the bu we can send the buffer as he is read buff no set buff take my look going to string copy to P from buff I think this will work right perhaps we need to cast this one and then we’ll simply return P we also want to print our um prompt let’s not forget about that so let’s do um print F and then our prompt and the space and we get the prompt right here and then we need to flush the buffer because we are not ending the printf line with the new line so we need to flush it manually standard out like so and here is our first version of that code did we create our uh yes but we didn’t make this an int8 this should be a Char okay so let’s let’s try it out without the echo with the Echo and where are we key equals read key thir key yeah let’s try it so [Music] make okay what is it differ in signedness P = buff plus index so it’s this line so P equals buff which is a Char so we need to do in a star plus index don’t think that will be a problem and PS let’s try it out okay we got a got a binary yeah okay so let’s try it out infile out file key AB c d uh we still have that pad size thing we can remove that but it seems to work okay guys uh let’s end there for today and we will continue this uh project another day don’t forget to like And subscribe and thanks for watching and thanks for today [Music] let’s that so print the PAD size let’s just delete that okay okay guys so now that we have our key retrieval function we will need to improve it a little bit and remove the echo of the keyboard characters from the screen so in order to do do that we need to use a function and that is located in an in a header file which is called the termal uh dot h and let me see if there are any examples let’s see okay so there doesn’t seem to be any examples but what we need to do is first because they’re in a terminal there are a couple of options that defines how the terminal should work so we need to do two function calls we need to retrieve the uh current options of your terminal uh then we need to alter one of the flags to remove the Echo and then we will uh do another call to change the flags so that’s how we talk hle the Echo and then we will just call our own function twice once for removing the Echo and once for uh getting the echo back so let’s see let’s begin by importing that H [Music] file it is called termal Doh we also need to create a function let it be a void function that we can call toggle Echo and we don’t really need [Music] any parameters like so so if the echo is enabled we remove it and if it is disabled we put it back uh perhaps we [Music] should yeah this will be easier let’s do a change Echo instead and then we will take a [Music] bull which will say if the echo should be enabled or disabled so we need to include the stdb as well like so so let’s write the function and this will be a void function that we call change Echo and we’ll have a bull enabled like this okay so the next step is we need to create a structure an instance of a structure uh for this kind of stuff and let let me see which one it is uh we’re going to use these two functions which means we need a struct terminals [Music] so let’s see and I closed the window let’s go into our directory it is called FS right no it’s inside temp FSE there we go okay so first I need to reset the home directory like that and we need a stct terminals T and let’s allocate some memory for it t equals stct [Music] terminal size of stct terminals like so let’s copy both of these function signatures to make it a little bit easier to to use them so first we call this get attribute so TC get attribute and the FD follows the same logic as standard in standard out standard error so this should be zero get attribute and then we have the T and that’s basically it perhaps we need to send a reference to the T let’s see if it works or not and let’s see what flag we need to alter I think it’s called Echo there’s a couple of them I think we just do the the echo okay so we need to do a binary operation so basically T is equal to no T the reference is equal to Let’s see we need to do um we need to remove a flag so we will do a logical and operation and that might seem a little bit in nonintuitive but basically if we have X and Y and we let one of them be zero then this will be zero as well if we use the uh or it would still be one so we remove Echo and now now way to we need to do an if first so if enabled then we’re going to add the flag no if it is enabled we’re going to remove it like we did and if it’s if it is disabled we want to enable it or what is most intuitive perhaps we should treat this enabl as if it should be enabled or not so if it should be enabled then we should do the or operation and remove the echo else we do the and operation and then we basically do the other one TC set attribute and we give the file descriptor in optional actions I think we can do the zero there and and then we need to give the structure construct terminals terminals yeah and that’s it so let’s see if this works in our not this one in our read key we will send the prompt then we going to do change Echo and we want to remove the Echo and then we will do it again change Echo and this time we want it to be enabled are true should be false up there right okay let’s see what [Music] happens make okay invalid upun to Binary or yes of course we don’t do it on the the whole structure we need to do it on one of the uh Fields inside that structure so let’s see which it is uh input modes output modes control modes so should either be the could be any one of these let’s see if we search for Echo and we go upwards to the headline C flag flag constraint constants okay so the same flags are for all of these or what did it say C flag okay let’s try it on the C flag it’s tough to remember all of these different functions that you only use once every couple of years let’s see where were we here so this looks right but we’re going to do T C flag and T C flag like so oh not TC flag it should be C flag only so right c c flag all a pointer we need the arrow not the dots let’s try it again TC UND declared T C flag okay now what invalid type argument un star have TC flag F AKA unsigned [Music] in well we should should probably not do reference that word where are we let’s do it like this okay so now we only have one error left has no member named C flag uh it’s tough to get this right huh it should be C FL see FL right let’s double check this time c i flag CC flag let’s copy this instead so remove the whole thing paste this in remove the whole thing paste this in this time I’m feeling lucky okay let’s try out we have infile we’ll have out okay didn’t really work Why didn’t it work perhaps it’s because of this zero or maybe they want us to do this on the standard out because logically it could really be either one right [Music] so make let me try it [Music] again nope Let’s do an S Trace it runs the command so let’s see the first time where is the first time here we get the flags and it has the echo then then we set the flags and do we have the echo no well yes it’s still there what is that let’s see [Music] so oh I forgot to free that one as well but that’s not the cause of the error let’s see so we get the flags if enabl and it’s should be [Music] false the first time read key change Echo false yes so so T see oh I mixed them didn’t I if it should be enabled we or if it should be disabled we end okay so let’s put this this way instead and let’s go back to the [Music] zero let’s try it again in file out file no let’s try it on standard out then so [Music] one one [Music] perhaps we shouldn’t do it on the C flag the other one what what did it say one has to do with input and one has to do with output input modes output mode is this an input mode or an output mode an echo well it’s both well let’s try it with an i input mode on the standard input so I flag and I flag if it should be enabled we add no we had this right the first time and we want to do it on the standard input the standard input okay something happened I can’t press enter anymore that’s pretty weird so we did change it somehow but not really the way I intended so let’s do the let’s just try one thing if we do one here and we do it on the I [Music] flag same thing so let’s do the I flag on [Music] the [Music] zero no for okay so get attributes file standard input okay so now I looked it up we should do it on the standard input as we thought but we should do it on the L flag so let’s try it [Music] again in file out file okay that’s bit weird no that’s not right either okay guys uh let’s end there for today and we will continue this uh project uh another day don’t forget to like And subscribe and thanks for watching and thanks for today [Music] sup guys welcome to Today’s Show today we are going to code a a safe string library and what is a safe string library and what why is it needed well if we let me show you an example so let’s say we have a main and I’m not going to do any error checking now so I will simply take the argument If This Were production code I would of course do a check so we don’t oh so we so we don’t access U parameters and command line arguments that’s not there uh let’s create a string let’s call it St uh and let it be eight in size and then we will create let’s do just a Char pointer and I will let it be equal to hello like this and I will include two files standard IO and the string Library like so okay so I want to put this uh P string into the Str Str variable so then I use string copy and the target is s Str and the source is p so this will copy the contents of P IE this hello and put it into our Str Str and then I will simply print F this Str Str like so and return zero okay let’s compile this and we run it no problem there [Music] right let’s oh sorry I’m going to use Nal today so you get a syntax highlighting uh okay so let’s instead well let me do like this if RC is less than two return minus one just a simple check and we’re going to take one argument from the standard input so instead of doing P equal hello I’m going to do p equal rv1 so we take the first command line uh argument we compile again and if we run it without any AR nothing happens what if we were to do the hello string again then it chose but what if we were to do something bigger than eight like this segmentation fault the program crashes why does this happen well these variables are placed on a stack if we and we don’t we only have room for eight characters in this variable so if we copy a lot of those with a string copy it will start to overflow the stack so basically it may over write variables in this case though the S strr is on the top of the stack so it will start uh overwriting other things like return addresses and saved stack pointers and other important stuff which basically means that the program will will not know how to how to return from this function and it will jump into some memory address which is not right and it will crash so a lot of when you’re dealing with strings a lot of the work is to make sure this doesn’t happen one possible solution to this is that instead of using the string copy like this you add an n in the middle so string n copy because then you can add a third argument which is uh the biggest number of characters to copy so if I put seven in here it can never copy more than seven characters so let’s try this again hello still works and if we do this now it will only do the first couple of characters and then exit without an error so if it’s this easy to fix this problem why bother with it why make a video about save string Library well this is only one example A lot of the times you don’t use functions like this you edit the strings yourself or what if you need to read all the lines in a file for example and put it inside of a string variable how would you do that you need to allocate and reallocate memory so you have the correct amount of memory all the time so it’s it’s not that straightforward to create a safe library for this okay so my plan is to make something that will work like this so let’s let’s remove stuff in here so I want to do something like this I want to create a string so this is my own uh variable and I will initialize Str Str with some initialization function like let’s call it in it and and it will take what will it take it will take a string to begin with so the first first string to put inside of this Str Str variable let’s say hello like so and I will not use any uh numbers so nothing like this that will only need five characters Etc I want to make this a library as easy to use as possible and what we wanted to add like hello the word there so it’s hello there then we can use a concatenation function so we just provide the string a variable name and then what we want to add to that uh string so let’s say uh there and then it will automatically take care of allocating the memory necessary in order to add this to the string and and if we want to print this string to the screen we can do this by just referencing uh let’s say well let’s call it fold and then we just give Str Str and it will will print the contents to the screen and then we only need some kind of um un initialization function so let’s say un init Str Str so we can easily use this conat inside of a loop and read an entire file it can be a very big file gigabytes or even larger and it will put it inside of this string construction that is the plan anyhow let’s see if we manage to do this I’m going to clean up a little bit here and create a simple make file so what do we need we’re going to have a file called Save St str. o which depends on Save S.C and we want to compile it using let’s see dollar roof or carrot or I’m not sure what how to pronounce it this means the source the C file in this case and this means the target the O and we’re going to do d c and yeah let’s not over complicate stuff that’s good and then we will have the safe string s o which depends on safe stram do o and then we will run CC and the source d o and this will be the [Music] Target and now we need a couple of options and I don’t have them in my head right now so I will use a variable which I call options which I will put some content into later on and when we do all I want to First clean and then make a safe St Str doso and finally I will put in the clean which will remove all the dot o files and the dot s f so something like this so if I just do touch and um let’s [Music] see save S.C I should be able to do make and it creates the we do get an error here but that’s only because we we have empty files this far make clean and it’s gone we also need a save st. H and I’m going to create a new window I’m going to go into code and save string I’m going to create set my home directory to this directory and then here I’m going to open the H file and in V save s str. h Save St Ag and then here I’m just going to open the cile so save s str. CC and we going to include our save s str. h like so and as usual I will Begin by defining my main so we’ll see what I want this to do so let’s create a string which we’ll call Str we’re going to initialize it like before using an init function which we hasn’t made yet and we will put in hello and then we want to concatenate yes are with the word there and yeah let’s do something like that to begin with anyway and then we want to un it St Str and in between we want to print it so print F perc s [Music] and fold St Str turn Z okay so this is basically what we want to achieve okay the first thing I’m going to do is include a couple of libraries just the standard ones so [Music] un htd H [Music] and this STD lib Ed include s. this is quite new by the way you might have to install the latest part of GCC if you want this so This adds native support for booleans [Music] H and I usually include string. H but I’m going to wait a little bit my hope is that I don’t need that and I can re write my own functions for that instead however I do need assert because I don’t want to worry too much with it error handling when I’m doing a video and I also need to do a definition for g source and that is so I get the function assert P error so basically this one function is inside of this file but it won’t be defined unless you define this one and it’s basically a combination of theed function and the P error the print error function which is quite nice I think but then you also need to include the r no number that H like so okay so let’s define our structure our string structure so I’ll call it s string and what do we need inside of this well we need some kind of a counter with so we know how many bytes of contents we have in our structure so let’s make this in unide in and we can call it count and we do also need the buffer the the actual string and this can be done a couple of different ways I could Define it as a Char pointer like this and then I allocate memory to this one but an even cooler way I think is to use a new function in later C versions that you can create a you can create a sh array basically string like uh what we going to call it data and usually you do something like this so you put like 64 so it will have 64 byes in it but if you put a zero in there then you define the variable but you don’t create any space for it which means that you can only do this at the end of the structure so this entire structure will be variable length and we can just increase and decrease the entire structure when we need to handle uh the strings which is kind of nifty I think okay and I will type def this instruct s string to string with capital S I will also create a couple of function definitions we have a main with an I’m not sure if I going to take any arguments but let’s put them here to begin with anyway and what else did we say we want an init function and that in it function will take a string an initial string and we want to return the pointer to a string so our own structure like so and then we want a concatenate function which will take a string pointer and another string and this will return a bull if it was successful or not and we also need an un initialization function but for the time being I think I’m going to do a Mac perhaps I need more intricate uh functionality later on so I’ll change that but for now I will just do this unit X will be 3 x like so so let’s start by creating our init function so it will return a string pointer and it’s called init and it takes a initial string like so and we need a size variable sign in size and size will be equal to length of Str Str so we do also need to Define that uh length function and that will basically be um let’s [Music] see that will basically [Music] be well it will be pretty much the same as the regular Str L right so unsigned in length and it takes a Char array we need an n and and a pointer let’s do the constate here and we create a pointer 4 m is equal to zero and P is equal to Sr we’re going to loop as long as let’s see as long as the thing that P points to is not zero and in each iteration we’re going to increase p and we’re going to increase n and we don’t need anything else no body of this one so I’ll add a semicolon at the end and then I’ll just return n and I want to create a function declaration for that as well so unsigned in length and it’ll take a Char star like so okay so now we have the length of the of the string and since this is the initialization function this will be the first uh string so we don’t have to think too much about it uh I do have however one one additional bite allocated and let’s allocate no so it will be this is how much we need for our string but then we also need the size of our structure which will be struct what did I name it s something s string okay that should be enough memory right so let’s create a string [Music] p p will be equal to string size like so and we do also need to zero this structure so one way of one new way of doing that wait first we need to assert that we p is not zero then we’re going to do a let’s [Music] see p I think it’s something like this P equals this I think you do it like that maybe we need to do reference let’s see if that works okay so we have the empty structure now we want to copy the actual string into there so name copy and into P data we want to copy the string [Music] and um let’s see we need a variable for the length so let’s do an n as well so n and size and we let N be equal to the length of this stram and we start substitute this by L which means we can copy n into the string and then we’ll just return P Okay so so let’s comment these out because we’re not done with them and not this one either with the initialization should be okay and let’s do a printf so we see that it it’s working so percent s and this will be St Str data like so okay let’s see what happens oh assignment discards con qualifier okay so let’s [Music] do I think it should be okay to add the con right here did I have the const here no I didn’t [Music] in we need a constant as well so cons basically means that we cannot write to the to that [Music] argument same here okay so con and maybe we don’t need it there [Music] okay discard con qualifier P equals s r okay we have a typo in the header file let’s see main that should be just in and what did we do wrong here let’s see it’s in the length function I [Music] think n = z p = s r p p++ n++ turn [Music] and let’s see what it’s let’s see what it [Music] said okay it didn’t look like this construct perhaps I need to add some options so it uses the new standard let’s see if we add Das s d [Music] equals m let me see c 2 x and let’s add it here as well SD = C2 X still doesn’t like it perhaps it needs the the space [Music] there expected expression plus [Music] P what if we do the slightly older standard and put a zero in there no still is not like that uh I think I need to type cast that’s probably it so let’s make it so and then I do string like so okay now it works M Copy okay what do we need for that M [Music] CP okay inside of the string. [Music] H let’s create our [Music] own [Music] no safe string let’s see so we have a void pointer and or let’s do Bo instead and we can name it copy it’s going to take [Music] a a void pointer to a destination going to take make a const vo source and the con sign in [Music] n and this function will basically be like this but not exactly but let’s start there anyway so cons Char [Music] P Let’s do let’s do like this so const sh [Music] p uh P source and just char No not Char void and right here we just do void T destination and we do a four [Music] where in X and inside here we set X = to n we set P Source equal to Source P destination equal to destination we’re going to iterate until X is z and and each direction we will increase P Source P source and [Music] p p destination and what are we going to do we’re going to take whatever P destination points to and set it to what P Source Point we can make this a void because not much can go wrong and if anything goes wrong then this program will crash so like so save and we need a function declaration so void copy and we have a void pointer for the destination we have a const void pointer for the source and we have a const [Music] unsigned in like so also we need to change so we use our own function where is our M Copy right here so let’s just do copy okay it’s getting better the referencing okay it doesn’t like the referencing void that’s right okay so let’s go into that file again and let’s let’s change the those pointers to char [Music] instead and let’s typ cast a little bit so so p c is equal to the Char version sour or the Cod Char version and this will be equal to the to the Char version of pest like so okay in main conflicting types that’s right we need to add our arguments in RC Char r or see like so and it compiles it does however compile into a library which is a little bit easy a little bit difficult to um to debug or to try out so let’s alter our make file a little bit and let’s change this this I don’t think we need to change anything else actually okay let’s see what happens segmentation fold okay let’s Trace s didn’t say much and L Trace didn’t say anything let’s double check the code let’s [Music] see save string. c s Str data so n equals length of the string I think we need to try out our two utility functions so we know that they work so we have our length and we have our M Copy let’s start with the length we check the length of a b c d e that should be five right okay no problem with that one so how do we check our mem copy in an easy enough way let’s create two Char buffers so buff one 16 and buff 2 16 and I’m going to string copy into buff [Music] one L and I’m going to then copy into F two from bu one and let’s see 2 three four five six n and then I’m going to print the content of um bu two I’m also going to memet both of them to zero them out like that and I need to add temporarily add [Music] the string Library [Music] set Oh wrong punctuation M there we go hello [Music] you okay so both of these function seem to work so how come my stuff doesn’t s Str equals index and print F St Str [Music] perhaps it’s about null termination yeah that’s probably it so where’s the NIT function how much am I alloc the m + 1 plus size of this so there’s room for the null [Music] Terminator let’s see if I if I create a regular sh pointer [Music] CH pointer Shar pointer should be equal to P data plus [Music] n then that should be a zero it should work I think still [Music] thanful hello take this string and equal length [Music] string size = n + one plus the size of this P equals [Music] string size [Music] P = [Music] stre [Music] zero copy P data the string and what happens if I remove this [Applause] slide okay so that’s where it seg FS down even though the copy function actually works so P data string n and n is the length of the string uh okay I forgot [Music] to I set the x to n and my idea was to decrease it and when it reaches zero we’re done but I only did half of that thought so we should add x- minus here as well all righty then then we probably don’t need this stuff since everything already should be zeroed out there we go yeah now it works as intended good sometimes it’s those small little things that makes you need have to trouble shoot forever okay where were we save string. C the only thing we have left actually is [Music] to is to create the concatenation function right which basically merges one of my strings with a regular string so let’s do this [Applause] and that is a [Music] bull and what did we call it we called it concat and it takes a string pointer as an argument and a const Char Source okay so first we need to calculate the memory consumption and we do need an unsigned in M which would be equal to the length of [Music] source so the size we we can make it in three steps let’s do a current sized as [Music] well so the current size is equal [Music] to the destination strings um count + one plus size of stct s string so the size of the structure and the contents that is a current size and the new size should be equal to the current size plus n the number of bytes we need to concatenate so then we have the new size we also need a pointer string p and let’s see no do really need that yes I think we do so p is equal to string and this time we use re look re look and the old memory segment is the destination yeah it’s a destination and the new memory requirements is the size that will be our p and if P fails we simply return false and if it doesn’t fail then we have the memory we need so now we just need to copy the new string so let’s do it basic like we did before I will create an let’s see I will create a regular CH pointer and that chart pointer should be equal to P data plus [Music] P count so basically it should be equal to the old count we need to increase by the with that so we come to the end of the old segment and that’s where we will uh put the new new date and then we will simply copy to P data no to CP and and what should we copy we should copy the source and how much of it it should be n like so and then we will simply do p count plus equals l so we increase the count and we return true that should basically be it right so let’s go down here I will remove this temporary print F and we’ll add back our concat and right we need this fold as well the fold should simply return the value let’s do it quick H Char Fone and it should take a string as an argument and it should simply return string data easy peasy let’s create the function definition as well so CH fold string star and we do have our only knit as well so maybe this compiles let’s see okay what does it say [Music] St St uh it should be S Str right where is it here concat s Str [Music] there uh we should add the serum but at the end when we [Music] conat so let’s [Music] see so CP should then be equal to P data plus the new P count and let’s zero that one like so compiles hold your breath almost it’s it’s showed the there but it didn’t it overwrote our old data I think I know why if we go to the emit function we don’t really increase the initial length so P count should be equal to l that’s right n + [Music] one yeah okay let’s try this again hello there okay so what have we learn today we have learned how to successfully create a a safe string library with a concatenation feature and uh some other stuff and I will leave as an exercise to you to create an equal function that you can use in order to check if two strings are equal and it should work with our string data type and regular strings in any combination if you like this content please like And subscribe there will be a lot of more uh see videos both beginner level and very Advanced I have a lot of interesting stuff in the pipeline so thanks for watching and thanks for [Music] today okay guys welcome back last week we began creating this taly tool which uh tunnels any Linux application through the tour Network we wrote the first part of it which is a socks version for client so this is what we have this far we can supply the destination host and Port so let’s take my web server as an example so we run talize and let’s do this IP with a port of 80 and we connect to the proxy maybe it’s a okay there there we go sometimes when you use the T Network it’s quite slow but more often than not it’s quite fast but as you can see we connected to the proxy we successfully connected through the proxy to the destination and we communicated with the web server on the other end so the biggest part is done what we need to do now is the following we need to turn the client into a library so instead of using an as an application we want to have it as a library and that is a shared library to be specifico files when we have done that we’re going to turn main into our own connect replace regular connect and we’re also going to save a reference to to the original connect so that we can use it ourselves because our current tool is using connect if we look right here so we connect to the proxy server using that uh system call and that’s why we need to save a reference to it so we can use it ourselves um we also need to grab the IP and Port from original connect so we will take care of the arguments that the uh application sends to its connect and and uh we need to take the IP and Port from there instead of reading it from the command arguments like we do now uh and then we can proceed by doing what we do now and then we will just uh leave it to the original application to take care of the uh the rest of the communication so we do our thing and then we exit our fun and let the program take over um okay so how does this technique work well when you compile your code you have two options you can compile it statically so it’s statically linked uh and that means that if you use any Library calls or system calls too for that matter like uh print F or anything that will be that code the print F code will be saved in your program’s uh executable file but that’s not very optimized because if every tool on the on the whole drive would be statically linked then there will be a lot of duplications because almost every application uses some form of Library calls or system calls so that’s why we have the shared libraries so instead of and that’s what’s usually in use so we have like a database with a lot of with a print F code and with a scan F code and even wrappers for system calls like connect and uh when an end application needs to use any of that code it will collect it from the central repository on the on the disk so that’s how it works the thing is there is a kind of um prioritization order so which we can influence so if there are two functions with the same name which one that’s going to execute is decided by a a list basically and a prioritization order so if we name our own function connect and uh we have compiled this as a shared library then we can make any application use our code AS PRI Priority One and in that way we can intercept and hijack the library call and system because all system calls have wrappers in the libraries okay this will probably be um a little more clear when we have written the actual code tested it and this is not my own invention this technique I am following a website let me just find it C shared Library function hook here it is at our Jordan a so it’s pretty simple actually so put s is a function which basically works like print F but not as it prints a single string on the screen so that’s the one that he uses in his example so as you can see he creates a function with the same name and same signature he creates a function pointer also with the same signature and that is for saving the original put s in this case and then he gets the reference from this dsim uh function so basically you give the rtld next and put and the name of the function and it gives back the memory address where that function is originally uh located in memory and uh then he just does like this so he checks if you send the argument hello world and in that case he hijacks the original pest call and changes the message in other case he just runs the uh original puts with the same arguments so this is basically what we’re going to do we’re not going to have a condition because we are always going to hijack the orig original one we are however going to use the original uh connect function to make our connection to the proxy server and uh then we compile it as a shared Library so there’s a couple of additional switches we use and then we get AO file and then we basically tell the system to use our uh Library instead by this LD preload environment variable so we’re going to create a small uh bash script in our case three lines big and um that’s what we’re going to name talize and uh then we’re going to use that to set the environment variable and run the command and uh yeah that should basically be it so let’s begin let’s start by Gra grabbing the um signature so we do man to connect and just copy this exactly as it is and then we go up to our main and just paste it right here like so and sock FD address l t and we remove this [Music] and so we basically turn our main function into this uh connect function like so and we create a function pointer and if you have watched my episode about function pointers you know that that is done like this I will paste the signature for this original original function once again and instead of connect I will just name this P for pointer I’ll put it inside parentheses and add the star and then then we remove this part so it should be basically like a like a signature function uh declaration and we use this to point to this DL Sims function and let me just see where it’s located so Man 3 DL Sims and if we don’t find it in page three we do page two weum perhaps it’s without the S yeah okay so it’s inside of this DL F cn. so let’s add that to our list of includes and let’s see if if he included anything else only the string so and I need to grab the first argument rtld Dore next and you might ask why um I don’t copy paste and I try to avoid that when possible because if I type this a couple of times I will will probably remember it ring next and the name of the function is connect like this and we initialize the socket but we don’t really or let’s do it like this by the way the the curl application or whichever we use have um already initialized their uh socket but I think it will be easier just to uh pipe those two sockets together okay so let me update the signature here as well so I don’t forget that by the way because we we don’t have any main anymore we just have in Connect it’s in right yes did I do in here yes okay so int connect int construct sock address star Su t uh so we don’t have a main anymore because that’s only for applications and this is not an application this is just a couple of functions which are free Okay so the application runs connect and we don’t need anything any of this and we save this we initialize our socket and uh here we make the connection to the proxy server nothing will change about that but we’re not going to call connect because we would be calling ourselves we will be calling this P the function pointer like so connected to proxy and we need we also need to change our request function uh instead of sending host and Port like we did before let me remove that so we have int s and we don’t have this host instead we need to grab the IP and the P Port from the arguments so this is what how what the application provides we have the socket file descriptor we have the length of this structure and we have the actual structure so I think the easiest way would be to I don’t want to name this address let’s call this let’s call it sock to and S2 instead so s and sock that’s ours and S2 and sock 2 are the the provided by the application so we need to look inside of this and get the data that we need so let’s pass the whole structure of that instead uh as host and Port so we’ll just do so two right here and we need to change the signature for our request function um and that is of type stru sock address [Music] in and star stct sock address in Star and I think we need to do a type cast and send the reference so where were we right here so struct sock address stct sock address [Music] in so to I think we need to do it like this if we get a warning or error we will change it but it should be all right struct address in sock 2 so we send that whole structure to this function and we need to change this as well so that will be struck sock address in let’s call it so no let’s call it sock to so we know what’s what okay so the destination Port we don’t need to do hton s and inet address because it’s already in the network bite order so the only thing we need to do is reference talk [Music] to sin port and for the destination IP so [Music] to S address Source address like so perhaps we need to do some type casting but I don’t think so in this case okay so now we have the correct packet and then we save that then we send that [Music] packet unable Traverse proxy we can keep this for now successfully connected through and this we will not have though so as soon as we are connected we are basically done we don’t want to close the socket we do however want to to pipe our socket with the end applications socket so what does it mean piping well we need to do so everything that’s being sent to S will also be sent to S2 and everything that’s being sent to S2 is being s to us and same with the receives so we basically become the man in the middle and there is a good system call which is called dup two which does exactly that um so it creates a new file descriptor and it will be the the same value as the second argument which means that this will be pretty seamless if we give S2 so D to S S2 and then we return the we forget anything I think we did most of it let’s copy the compilation flags from this [Music] one so we’ll go into our make file and this will be [Music] to.so F pictured LDL okay and I will Begin by removing the talize binary executable because that won’t be necessary okay let’s see what it says if we try to compile this one okay DL Sims it should be DL Sim right here and I enter down a little bit and it runs make again and host UND declared okay that’s the message don’t think we actually need that one where is it uh unable to Traverse the proxy successfully connected through the proxy let’s just say through the proxy enter otherwise we need to convert between Network by order and stuff like that perhaps we can change this later on instead if we want to okay it compiled so how are we going to test this we haven’t really created our bash script we can do that now by the way let’s begin by checking what directory we’re we’re in and the name of this so I’ll just do a copy paste of this directory and I will add thiso file to it so this is the whole path to our library and I will log in as the root user I will go to user bin and I will open up Tora lies and this will be a bash [Music] file so we need to have this interpreter at the top or the hashbang uh okay so let’s export LD pre load to this one and then we want to run the commands because we’re going to run this as talize and then curl or whatever so we need to send everything that’s on the right of this toriz and there is a way to access all the arguments at the same time and I I think it is done like this okay so first we export the LD preload and point it towards our shared library then we do the dollar and I think it’s the at sign which will run all the arguments to this uh script and finally we unset the LD preload like this it’s probably not necessary to unset it because it’s the end of the script but I think it’s looks a little better all right so we save this and give it running permissions toiz and then we test it out and hope that it works so Network technology.org we will try to do talize curl and an HTTP request against this IP address connected to proxy uh couldn’t connect the server let’s try restarting the tour perhaps it’s a bad uh connection that happens sometimes so tour restart okay and then we try it again okay connected to proxy this time it didn’t even give an error message let’s see what this error code 91 is if we go back to the RFC so RFC socks 4 and we go down here request rejected or failed I will try once again to restart the service perhaps we are unlucky with the connection so let’s do like this and then we run toye again at least it’s able to intercept the connect function as we can see by this connected to proxy but it doesn’t really succeed in connecting let’s just see that this one is up and running yes and it’s lessening on Port a right let’s do just like this okay I don’t have tet here let’s run it from from this instead so and tet this 80 okay it’s the server that’s not responding that’s weird post let’s try something else let’s do I think we should be able to do a a regular host name this is a Swedish site that shows uh the IP if you if we do make this work though that’s not going through the tour Network the actual DNS request so the DNS request probably goes outside of the tour Network and then the actual IP uh connection goes through so current connect to server weird does anything work Google see yeah there’s nothing wrong with the routing but we need to try something else what if we do a host on this site and we talize a curl HTTP and this IP instead are we able to connect directly to this one okay that works let’s let look through the code perhaps we did miss something so what happens right here we set this to the regular connect function we initialize a new socket and we connect to the proxy with the proxy port using this connect the regular connect function and and we managed to get connected to the proxy everything is fine this far perhaps something perhaps there’s some problem with where we when we grab the IP address so R request stct sock address in perhaps we should not send the reference what if we were to do like this [Music] instead CD code and to and we need to run make and then we do [Music] host and we do talize H curl HTTP and this IP okay so now it works and we should be able to see the IP here I think somewhere okay it seems that we go through some kind of middle server it probably only works against Swedish IP addresses and we probably don’t come from the Swedish IP through the tour Network we need to try something else what if we were to do F we can test regular first so if we do [Music] host what is my ip.com [Music] we do a regular curl and we get an error code okay we need to send the host name and I don’t think that’ll work but let’s try it again uh so curent or it will work when you do right here but I don’t think we will get a response no let’s just do Google them so host Google go. I’m going do tour allies Cur HTTP and this IP okay that works what if we do a host name does it even try to resolve that yeah it works but as I said be careful by doing that because only the IP connection will be private not the DNS request but as you can see we are able to um Traverse the proxy and we are able to talize any command using this tool so that’s the end of this series I hope you want to sub subscribe and like if you think it’s it deserves it and uh there will be more interesting videos in the future thanks for watching and thanks for today

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

  • JavaScript Fundamentals: Console, Variables, Data Types, and Objects

    JavaScript Fundamentals: Console, Variables, Data Types, and Objects

    The provided text is a guide to understanding JavaScript programming concepts. It covers a range of topics, beginning with how to use the console for debugging. The text then explores fundamental concepts such as variables, data types (primitive and reference), type coercion, and operators. It discusses strings, numbers, arrays, and objects, including methods to manipulate them. Finally, it introduces functions, scope, DOM manipulation, and event handling, along with keyboard events.

    JavaScript Fundamentals Study Guide

    Quiz

    1. What are the three core technologies of the web?
    2. Explain the difference between interpreted and compiled code.
    3. Briefly describe the Document Object Model (DOM).
    4. What is an asynchronous request, and why is it useful in web development?
    5. What is the purpose of the parseFloat() function? How does it differ from parseInt()?
    6. Explain the concept of “truthy” and “falsy” values in JavaScript, and give one example of each.
    7. What does NaN represent in JavaScript, and list two operations that result in NaN.
    8. Describe what the modulus operator (%) does.
    9. Explain the difference between == and === comparison operators in JavaScript.
    10. What is type coercion in JavaScript, and how does it differ from type conversion?

    Quiz Answer Key

    1. HTML, CSS, and JavaScript. HTML structures web content, CSS styles the content, and JavaScript brings interactivity to the front-end.
    2. Interpreted code is executed line by line, while compiled code is first translated into machine code before execution. JavaScript is an interpreted language, making it a scripting language.
    3. The DOM is a tree-like structure of nodes representing everything on a web page, including HTML tags, attributes, and text. JavaScript can manipulate the DOM to dynamically change the content and styles of elements.
    4. An asynchronous request allows a web page to interact with a back-end server without requiring a page refresh. This is useful for dynamically loading and updating content, particularly in single-page applications.
    5. The parseFloat() function converts a string to a floating-point number. parseInt() converts a string to an integer, discarding any decimal portion.
    6. Truthy values are values that evaluate to true in a Boolean context (e.g., 1, “hello”), while falsy values evaluate to false (e.g., 0, null, undefined, “”).
    7. NaN stands for “Not a Number,” representing a value that is not a valid number. Operations such as parsing a non-numeric string with parseInt() or parseFloat(), or square root of a negative number result in NaN.
    8. The modulus operator (%) returns the remainder of a division operation. For example, 7 % 5 equals 2.
    9. The == operator compares two values for equality after type coercion, meaning JavaScript might try to convert the values to a common type before comparing them. The === operator compares two values for equality without type coercion, meaning the values must be of the same type to be considered equal.
    10. Type coercion is the implicit conversion of one data type to another by JavaScript, often when applying operators to values of different types. Type conversion is the explicit conversion of one data type to another by the developer, using functions like String(), Number(), and Boolean().

    Essay Questions

    1. Discuss the versatility of JavaScript and the reasons for its popularity in modern web development.
    2. Explain the differences between client-side and server-side JavaScript. Give examples of frameworks or environments associated with each.
    3. Describe the concept of scope in JavaScript, differentiating between global, function, and block scope. Use examples to illustrate how variable access changes in different scopes.
    4. Explain the execution context in JavaScript, including the memory creation phase and execution phase. How does the execution context differ when invoking a function?
    5. Describe the different types of keyboard events in JavaScript and how they are used. Include details about properties like key, keyCode and code and how to use modifier properties such as shiftKey, ctrlKey and altKey.

    Glossary of Key Terms

    • API (Application Programming Interface): A set of rules and specifications that software programs can follow to communicate with each other.
    • Asynchronous Request: A request that doesn’t block the execution of other code while waiting for a response.
    • Boolean: A data type with two possible values: true or false.
    • Client-Side JavaScript: JavaScript code that runs in the user’s web browser.
    • Compiled Code: Code that has been translated into machine code by a compiler before execution.
    • CSS (Cascading Style Sheets): A style sheet language used for describing the presentation of a document written in a markup language like HTML.
    • 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: An action or occurrence recognized by a software system, often originating asynchronously from the external environment, such as a mouse click or key press.
    • Expression: A combination of values, variables, operators, and function calls that evaluates to a single value.
    • Falsy Value: A value that evaluates to false in a Boolean context (e.g., 0, “”, null, undefined, NaN).
    • Function: A block of organized, reusable code that performs a specific task.
    • Global Scope: The scope that contains variables that are declared outside of any function or block.
    • Hoisting: The JavaScript mechanism where declarations of variables and functions are moved to the top of their scope before code execution.
    • HTML (HyperText Markup Language): The standard markup language for creating web pages.
    • HTTP Request: A request made by a client to a server to access resources or perform actions.
    • IIFE (Immediately Invoked Function Expression): A JavaScript function that runs as soon as it is defined.
    • Interpreted Code: Code that is executed line by line by an interpreter.
    • JavaScript: A high-level, interpreted programming language primarily used for creating interactive web pages.
    • Local Storage: A web storage API that allows web applications to store data locally within the user’s browser.
    • NaN (Not a Number): A value representing an undefined or unrepresentable value, typically resulting from invalid mathematical operations.
    • Node.js: A JavaScript runtime environment that allows JavaScript to be used on the server side.
    • Operator: A symbol that performs an operation on one or more operands (values or variables).
    • Scope: The context in which variables and functions are accessible.
    • Server-Side JavaScript: JavaScript code that runs on a server rather than in a client’s web browser.
    • Single-Page Application (SPA): A web application that loads a single HTML page and dynamically updates the content without requiring page reloads.
    • Truthy Value: A value that evaluates to true in a Boolean context (e.g., 1, “hello”, {}).
    • Type Coercion: The automatic or implicit conversion of values from one data type to another in JavaScript.

    Modern JavaScript Fundamentals

    Okay, I have reviewed the provided source and have created a briefing document summarizing its main themes and key ideas.

    Briefing Document: JavaScript Course Excerpts

    Overview:

    This document summarizes excerpts from the beginning of a “Modern JavaScript from the Beginning” course. The course aims to provide a comprehensive understanding of JavaScript fundamentals. The initial sections cover basic concepts, data types, operators, control flow, functions, scope, events and date objects as well as introduction to arrays and objects (object literals). The presenter emphasizes that even experienced developers might find value in revisiting these core principles.

    Main Themes and Key Ideas:

    1. What is JavaScript?
    • JavaScript is a core technology of the web, alongside HTML (structure) and CSS (styling).
    • It brings interactivity and dynamism to web pages.
    • It can be used server-side with Node.js to interact with databases and file systems.
    • It’s an interpreted (executed line by line), high-level scripting language.
    • “JavaScript is one of the core Technologies of the web alongside HTML which is a mock-up language and is used to structure web page content as well as CSS which is used to style that content so JavaScript is what brings life to the front end or the user interface of a website or a web app”
    1. Uses of JavaScript (Client-Side & Server-Side):
    • DOM Manipulation: Dynamically changing the structure, content, and styles of HTML elements. The DOM is viewed as a tree-like structure of nodes.
    • “JavaScript provides methods for dynamically changing that structure or changing the content or the styles of the elements in the Dom”
    • Event Handling: Responding to user actions like mouse clicks, keyboard input, and form submissions.
    • “…JavaScript gives us a way to handle events so we can respond to things like Mouse clicks or drags or hovers keyboard events form submissions and just about anything you can think of that you can do in the browser window”
    • Asynchronous Requests: Interacting with back-end servers and APIs to fetch or submit data without page reloads. Common in Single Page Applications (SPAs).
    • “making asynchronous request is one of the most powerful uses of JavaScript and it’s used to interact with back-end servers”
    • Animations & Effects: Creating visual effects using CSS transitions, JavaScript methods, and libraries.
    • Data Manipulation: Sorting, filtering, and transforming data using array methods (map, filter, reduce).
    • “…data manipulation which is the process of modifying or transforming data can be done with JavaScript because it’s a full-featured language with data structures like arrays”
    • Data Storage: Storing data in the browser using local storage, session storage, and cookies.
    • Single Page Applications (SPAs): Building applications that load a single HTML page and dynamically update content. Often used with front-end frameworks (React, Vue, Angular).
    • “JavaScript can also be used to store data on the client or in the browser using things like local storage session storage and cookies we can also create single page applications or spas and these are applications that load a single HTML page and dynamically update the content without having to reload the entire page”
    • Server-Side (Node.js/Deno): Creating APIs that interact with databases. Frameworks like Express.js are mentioned.
    1. Why Learn JavaScript?
    • Popularity: Widely used language with a large community, making it a valuable skill for job opportunities and collaboration.
    • “popularity JavaScript is one of the most widely used programming languages with millions of developers using it to build websites web applications browser-based games server-side apis and more”
    • Versatility: Can be used for a wide range of applications.
    1. Data Types and Type Conversion/Coercion:
    • JavaScript has data types like numbers, strings, and Booleans.
    • Type Conversion: Explicitly changing a data type using constructors (e.g., String(), Number(), Boolean()) or methods like parseInt() and parseFloat().
    • “…if you have a decimal right so if let’s say this is amount is 99.5 and you want to let’s say it’s a string of 99.5 and you want to convert it to a number of 99.5 which is a decimal there’s a method you can use called parse float”
    • Truthy and Falsy values: Discusses truthy and falsy values. Zero is a falsy value.
    • NaN (Not a Number): Results from operations that cannot produce a valid number (e.g., parsing a non-numeric string). It is a special number type.
    • “…we get a value of Nan or Nan and what this stands for is not a number okay it’s uh it’s actually a special number as you can see it does have the type of number but it’s a special number that represents not a number”
    • Type Coercion: Implicit conversion of data types during operations, often when using operators with different types.
    1. Operators:
    • Arithmetic Operators: +, -, *, /, % (modulus), ** (exponentiation).
    • Concatenation Operator: + (used to join strings).
    • “the concatenate operator is the plus sign so you can essentially think of the plus sign having two different functions in JavaScript one obviously is addition but one is to concatenate strings together”
    • Increment/Decrement Operators: ++, –.
    • Assignment Operators: =, +=, -=, *=, /=, %=, **=.
    • Comparison Operators: == (equal to), === (equal value and type), != (not equal to), !== (not equal value or type), >, <, >=, <=. The presenter recommends using === and !== to avoid potential issues.
    • “what I do and what I’ve what I see a lot of people do is pretty much always use the triple equals I think that that’s going to save you some headaches and save you some hours if you just always use triple equals”
    1. String Methods & Properties:
    • Strings are primitive, but JavaScript provides a wrapper object allowing the use of methods and properties.
    • length: Property to get the string’s length.
    • Accessing Characters: Using bracket notation (e.g., str[0]) or charAt().
    • “…if I say x equals and then S I can use this syntax and it starts at zero just like an array if I save that you’ll see I get H I get the first character if I do one I get e so I get the second character and so on”
    • toUpperCase(), toLowerCase(): Changing case.
    • indexOf(): Finding the index of a character or substring.
    • “if we want to know the index of a specific character so kind of the the inverse of this we could say s equal x equals s and we can use index of”
    • substring(), slice(): Extracting portions of a string. Slice can use negative indices to start from the end.
    • “substring which will search a string for a specified value so let me show you if we do s dot and then substring and then we can this will take in two indexes so let’s say we want to get from 0 to 4”
    • trim(): Removing whitespace from the beginning and end of a string.
    • “trim and what this does is it trims the white space”
    • replace(): Replacing a substring with another string.
    • includes(): Checking if a string contains a substring (returns true or false).
    • “…if I say s dot includes and we want to let’s say we want to find hello if I save that we’re going to get true because this is found within that s string”
    • valueOf(): Returns the primitive value of a String object.
    • split(): Splitting a string into an array based on a separator.
    • “split which you I use I’ve used quite a bit it’ll split a string into an array and it takes in a separator as an argument”
    • Prototype: Where the methods are stored.
    1. Number Methods and Properties
    • toString(): Returns a string representation of a number.
    • toFixed(digits): Formats a number using fixed-point notation, rounding to the specified number of digits after the decimal point. Returns a string.
    • toPrecision(precision): Formats a number to a specified length.
    • toExponential(fractionDigits): Returns a string representing the number in exponential notation.
    • toLocaleString(): Returns a language-sensitive representation of the number.
    • Number.MAX_VALUE: The maximum numeric value representable in JavaScript.
    • Number.MIN_VALUE: The smallest positive numeric value representable in JavaScript.
    1. Math Object:
    • Built-in object for mathematical operations.
    • Math.sqrt(): Square root.
    • “…we want to get the the um the square root of a number so we’ll do math Dot and then sqrt”
    • Math.abs(): Absolute value.
    • Math.round(): Rounds to the nearest integer.
    • Math.ceil(): Rounds up to the nearest integer.
    • Math.floor(): Rounds down to the nearest integer.
    • “…we can do the opposite and round down with the floor method so if I were to do math dot floor obviously that’s going to give me 4 but if I even if I do like 4.9 and I save that’s still going to give me 4”
    • Math.pow(): Raises a number to a power.
    • Math.min(), Math.max(): Finds the minimum or maximum of a set of numbers.
    • Math.random(): Generates a random decimal number between 0 (inclusive) and 1 (exclusive). Demonstrates how to generate random numbers within a specific range.
    • “a really common method is the random method so let’s say x equals math Dot random”
    1. Date Objects:
    • Creating date objects: using new Date().
    • Date formats: Demonstrates creating dates with arguments (year, month, day, hour, minute, second) and with date strings. Notes a potential time zone issue when using hyphens and year-first format.
    • “…if I do a string so quotes here 20 21 let’s say Dash zero seven and let’s say 10. if I save that then we’re going to get July”
    • Timestamps: Discusses Unix timestamps (milliseconds since January 1, 1970). Date.now() gets the current timestamp. getTime() or valueOf() gets the timestamp of a specific date.
    • “…what it is it’s an integer that represents the number of seconds that’s elapsed that’s passed since the date of January 1st 1970 which is an arbitrary date”
    • “…you can always get the time stamp by using let’s say d so by using date dot now like that so if I save that we’re going to get the milliseconds that have passed if I reload you’ll see it’ll just keep updating right so that that gives you a way to always be able to mark an exact you know millisecond in time”
    • Methods for getting parts of a date: getFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes(), getSeconds(), getMilliseconds(). Month is zero-based.
    • “if you want to get specific parts of the date we can do that so let’s say we want to get the the year so we’ll do D dot and then there’s a get full year method and you can see it gives us 2022”
    • toLocaleDateString(), toLocaleString(): More modern and powerful ways to format dates in a locale-sensitive way.
    1. Arrays and Objects
    • Section introduction: Will cover creating, manipulating and nesting arrays and objects.
    1. Scope
    • Global Scope, Function Scope, Block Scope
    • Variable Shadowing – when a variable in a local scope has the same name as a variable in the outer scope.
    • VAR is function scoped, not block level scoped.
    • Variables declared with VAR are added to the window object. Variables declared with LET and CONST are not.
    • “…when we create a global variable with VAR if we look at the window object let’s take a look here you’ll see that it actually gets added to the window object when we use letter cons that does not get added to the window object so you can see here there’s no Foo”
    • Nested Functions – child functions can access parent variables.
    1. Functions
    • Function Declaration – start with the function keyword
    • Function Expression – function assigned to a variable
    • Arrow Functions – shorter syntax for writing functions
    • IIFE (Immediately Invoked Function Expression) – function that runs as soon as it is defined.
    1. Logic and Control Flow
    • IF statements
    • IF ELSE statements
    • Truthy and Falsy values
    • Logical Operators
    • SWITCH statements
    • TERNARY Operator
    1. Events
    • Adding event listeners
    • MOUSE Events
    • KEYBOARD Events
    • Different keyboard properties to detect key presses and states

    Challenges:

    • Capitalize Challenge: Capitalize the first letter of a single-word string.
    • Min Max Challenge: Create a function that takes an array of numbers and returns an object with the minimum and maximum values.
    • IIFE Challenge: Create an IIFE that takes in the length and width of a rectangle and logs its area to the console.
    • Random Number and Math Challenge: Create random numbers and calculate their sum, difference, product, quotient, and remainder, then log the results in a specific format.

    Overall Impression:

    The course excerpts promise a solid foundation in JavaScript, starting with fundamental concepts and progressing towards more practical applications. The instructor emphasizes understanding the “why” behind the code, not just the “how,” and provides a blend of explanations, examples, and challenges to reinforce learning.

    JavaScript Fundamentals and Usage Guide

    ### What is JavaScript and what is it used for?

    JavaScript is a high-level, interpreted programming language that is one of the core technologies of the web, alongside HTML and CSS. It is primarily used to add interactivity and dynamic behavior to websites. It can also be used on the server-side with Node.js and Deno to interact with databases and the file system. Some general uses include manipulating the DOM, handling events, making asynchronous requests, creating animations and effects, data manipulation, storing data, and building SPAs.

    ### What is the DOM (Document Object Model) and how does JavaScript interact with it?

    The DOM is a tree-like structure of nodes representing the HTML elements on a webpage. JavaScript allows developers to dynamically change the structure, content, and styles of elements in the DOM. This includes adding, removing, or modifying text, content, and styles (like color, font, and size). Manipulating the DOM is a fundamental aspect of creating dynamic and interactive web pages.

    ### How can I convert data types in Javascript?

    JavaScript has constructors that allow you to convert values to specific data types. The `String()` constructor converts a value to a string, `parseFloat()` converts a string to a decimal number, and `Boolean()` converts a number to a Boolean value (true or false). Zero is falsy, and one is truthy. Converting a non-numeric string using `parseFloat()` will result in “NaN” (Not a Number).

    ### What are operators in JavaScript and what are some common types?

    Operators are symbols that perform specific operations in JavaScript expressions. Common types include:

    * **Arithmetic Operators:** `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `%` (modulus – remainder), `**` (exponentiation), `++` (increment), `–` (decrement).

    * **Assignment Operators:** `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `**=`.

    * **Comparison Operators:** `==` (equal to), `===` (equal value and type), `!=` (not equal to), `!==` (not equal value or type), `>` (greater than), `<` (less than), `>=` (greater than or equal to), `<=` (less than or equal to).

    * **Logical Operators:** `&&` (AND), `||` (OR), `!` (NOT)

    ### What is type coercion in JavaScript?

    Type coercion is the automatic or implicit conversion of values from one data type to another in JavaScript. It typically occurs when operators are applied to values of different types. For example, when adding a number to a string, JavaScript might convert the number to a string before concatenating them.

    ### How do I find the length of a string?

    Strings have a length property. `string.length` will produce the length of the string.

    ### What are some methods available on strings in Javascript?

    Strings have a prototype where methods are stored. Strings have methods for changing case (`toUpperCase()`, `toLowerCase()`), finding characters by index (`charAt()`), finding the index of a character (`indexOf()`), extracting portions of a string (`substring()`, `slice()`), removing whitespace (`trim()`), replacing substrings (`replace()`), checking for inclusion (`includes()`), and splitting a string into an array (`split()`).

    ### How can I generate a random number in JavaScript?

    The `Math.random()` method returns a random decimal number between 0 (inclusive) and 1 (exclusive). To generate a random number within a specific range, you can multiply `Math.random()` by the range and then use `Math.floor()` to round down to the nearest whole number.

    “`javascript

    let randomNumber = Math.floor(Math.random() * 10) + 1; // Generates a random number between 1 and 10

    JavaScript Console: A Developer’s Tool

    The JavaScript console is a tool available in web browsers that allows developers to log information, debug code, and execute JavaScript commands.

    Key aspects of the JavaScript console:

    • Access: Accessed through browser’s developer tools (e.g., in Chrome, More Tools -> Developer Tools). Can be directly accessed using keyboard shortcuts such as Command + Option + J on Mac.
    • Functionality:
    • Displaying Warnings and Errors: Shows warnings and errors generated by front-end JavaScript code, indicating the line number and file of origin.
    • Logging Information: Allows logging of data and messages from a script using the console object.
    • Executing JavaScript: Enables running JavaScript code directly in the console.
    • The console Object: The console object in JavaScript contains methods for interacting with the console.

    Commonly used console object methods:

    • console.log(): Logs information to the console. It can output different data types like numbers (e.g., 100), strings (e.g., “Hello World”), and booleans (true or false). It is possible to log multiple values simultaneously by including them as arguments.
    • console.error(): Logs an error message to the console, often with a red background or border.
    • console.warn(): Logs a warning message to the console, typically with a yellow background.
    • console.table(): Displays data in a tabular format, useful for visualizing objects with key-value pairs.
    • console.group() / console.groupEnd(): Creates a collapsible group in the console to organize related log messages.
    • console.clear(): Clears the console. It can also be cleared using keyboard shortcuts such as command/control + L.

    Additional features:

    • Styling Console Logs: CSS styles can be applied to console logs using the %c specifier, followed by the desired CSS rules as a second argument to console.log().
    • Accessibility: The console is primarily a tool for developers and is not intended for end-users of a website.

    JavaScript Data Types: A Comprehensive Guide

    In JavaScript, data types define the kind of values that can be stored and manipulated within a program. JavaScript is a dynamically typed language, meaning that you do not have to explicitly define the data types of variables.

    There are two main categories of data types in JavaScript: primitive types and reference types (or objects).

    Primitive Data Types:

    • Primitive types are immutable, meaning their values cannot be changed after creation. When a primitive type is assigned to a variable, the variable is given a direct copy of the value. These values are stored directly in the memory location known as the stack.
    • JavaScript has seven primitive data types.
    • String: Represents textual data and is a sequence of characters enclosed in single or double quotes (e.g., “Hello, World!”).
    • Number: Represents numeric values, including integers and floating-point numbers (e.g., 30, 98.9). There is no distinct type for integers or decimals; all numbers are of the Number type.
    • Boolean: Represents a logical value that can be either true or false.
    • Null: Represents the intentional absence of any object value. It indicates that a variable has been intentionally set to “no value.” Confusingly, the typeof operator returns “object” for null, which is considered a historical artifact or mistake in JavaScript.
    • Undefined: Represents a variable that has been declared but has not been assigned a value. The type of such a variable is also undefined.
    • Symbol: Represents a unique and immutable value, often used as object properties.
    • BigInt: Represents integers of arbitrary precision, allowing for the storage and manipulation of numbers larger than the Number type can handle.

    Reference Data Types (Objects):

    • Reference types are mutable, and when a reference type is assigned to a variable, the variable is given a reference to that value. These values are stored in the heap.
    • Objects are collections of key-value pairs. Object literals, arrays, and functions are examples of reference types.
    • Object Literal: A basic object in JavaScript, containing properties defined as key-value pairs, enclosed in curly braces {}.
    • Array: An ordered list of values.
    • Function: A callable object that executes a block of code. Functions are also considered objects in JavaScript, with the type of operator returning “function”.

    Type Detection:

    • The typeof operator can be used to determine the type of a variable. For example, typeof firstName will return “string” if firstName holds a string value. However, typeof null returns “object” due to historical reasons.

    Dynamic Typing:

    • JavaScript is a dynamically typed language, meaning that variable types are not explicitly defined and can change during runtime.
    • Type Conversion: It is possible to explicitly convert a value from one type to another. For instance, converting a string to a number using parseInt() or the unary plus operator (+).
    • Type Coercion: JavaScript can also implicitly change types during operations. For example, when adding a number and a string, JavaScript may coerce the number into a string.

    Understanding data types is crucial for writing correct and efficient JavaScript code. Knowing the differences between primitive and reference types, how they are stored, and how type conversions occur helps in avoiding common pitfalls and writing robust applications.

    JavaScript Variable Declaration Guide

    In JavaScript, declaring a variable means creating a named storage location in memory that can hold a value. When declaring variables, there are three keywords that can be used: var, let, and const.

    Here’s a breakdown of variable declaration in JavaScript:

    • Keywords:
    • var: The original keyword for variable declaration.
    • let: Introduced in ECMAScript 2015 (ES6), it is used for block-scoped variable declarations.
    • const: Also introduced in ES6, it is used for declaring constants, which are variables whose values cannot be reassigned after initialization.
    • Scope:
    • Global Scope: Variables declared outside of any function or block have global scope.
    • Function Scope: Variables declared with var inside a function have function scope. They are accessible only within that function.
    • Block Scope: Variables declared with let or const inside a block (e.g., within an if statement or a loop) have block scope. They are accessible only within that block.
    • Basic Syntax:
    • To declare a variable, you use one of the keywords (var, let, or const) followed by the variable name. For example:
    • var firstName;
    • let age;
    • const PI = 3.14159;
    • Initialization:
    • Variables can be initialized at the time of declaration by assigning them an initial value using the assignment operator (=).
    • let firstName = “John”;
    • const age = 30;
    • Variables declared with let can be declared without immediate initialization.
    • Constants (const):
    • Variables declared with const must be initialized during declaration.
    • const GRAVITY = 9.8; // Correct
    • // const E; // Error: Missing initializer in const declaration
    • Constants cannot be reassigned after initialization.
    • const PI = 3.14;
    • // PI = 3.14159; // Error: Assignment to constant variable.
    • It is possible to modify the properties of an object or array declared with const, but it is not possible to reassign the variable itself.
    • const myArray =;
    • myArray.push(4); // Valid: myArray is now
    • const person = { name: “John” };
    • person.name = “Jane”; // Valid: person.name is now “Jane”
    • // myArray =; // Invalid: Reassignment of const variable
    • Naming Conventions:
    • Variable names can contain letters, numbers, underscores, and dollar signs.
    • Variable names cannot start with a number.
    • JavaScript uses camel case as a common convention for variable names (e.g., firstName, lastName).
    • Hoisting:
    • Variables declared with var are hoisted to the top of their scope, meaning they can be used before they are declared in the code. However, they are initialized with undefined until the line where they are assigned a value.
    • Variables declared with let and const are also hoisted, but they are not initialized. Using them before their declaration results in a ReferenceError.
    • Multiple Declarations:
    • It is possible to declare multiple variables in a single statement.
    • let a, b, c;
    • const x = 10, y = 20, z = 30;
    • However, it is generally recommended to declare each variable on a separate line for better readability.

    JavaScript Object Literals: Comprehensive Guide

    Object literals are a fundamental concept in JavaScript used to create objects, which are collections of key-value pairs. They are a primary way to define objects in JavaScript.

    Here’s a detailed discussion of object literals, drawing from the sources:

    • Definition: An object literal is a way to create a new object in JavaScript using a simple, concise notation. It involves defining properties (key-value pairs) within curly braces {}.
    • Syntax:
    • An object literal consists of key-value pairs, where keys are strings (or symbols) and values can be any data type, including primitive values, other objects, or functions.
    • Keys and values are separated by a colon :, and each key-value pair is separated by a comma ,.
    • Example:
    • const person = {
    • firstName: “Brad”,
    • age: 40
    • };
    • In this example, person is an object with two properties: firstName with the value “Brad”, and age with the value 40.
    • Properties and Methods:
    • Properties are the key-value pairs that store data within the object.
    • Methods are functions that are associated with an object and can be called using dot notation.
    • Accessing Properties:
    • Properties of an object can be accessed using dot notation (objectName.propertyName) or bracket notation (objectName[“propertyName”]).
    • console.log(person.firstName); // Output: Brad
    • console.log(person[“age”]); // Output: 40
    • Nesting Objects:
    • Objects can be nested within other objects, allowing for complex data structures.
    • const person = {
    • name: “Brad”,
    • address: {
    • street: “123 Main St”,
    • city: “Anytown”
    • }
    • };
    • console.log(person.address.city); // Output: Anytown
    • Adding or Changing Properties:
    • Properties can be added to an object or their values modified after the object has been created using dot or bracket notation.
    • person.email = “brad@example.com”; // Adding a new property
    • person.age = 41; // Modifying an existing property
    • Using Functions as Methods:
    • Functions can be added as methods to object literals. The this keyword can be used within a method to access other properties of the object.
    • const person = {
    • name: “Jane Doe”,
    • greet: function() {
    • console.log(`Hello, my name is ${this.name}`);
    • }
    • };
    • person.greet(); // Output: Hello, my name is Jane Doe
    • Object Constructor:
    • Another way (besides object literals) to create objects is to use the object constructor.
    • let todo = new object ();
    • This creates an empty object to which properties can be added with dot notation such as todo.id = 1;
    • Enhanced Object Literals (ES6):
    • ES6 introduced several enhancements to object literals, including shorthand property names and computed property names.
    • Shorthand Property Names: If the property name is the same as the variable name, you can use a shorthand notation.
    • const firstName = “John”;
    • const age = 30;
    • const person = {
    • firstName, // Shorthand for firstName: firstName
    • age // Shorthand for age: age
    • };
    • Spread Operator:
    • The spread operator (…) can be used to copy properties from one or more objects into another object.
    • const obj1 = { a: 1, b: 2 };
    • const obj2 = { c: 3, d: 4 };
    • const obj3 = { …obj1, …obj2 };
    • console.log(obj3); // Output: { a: 1, b: 2, c: 3, d: 4 }
    • Object.assign():
    • The Object.assign() method is another way to merge the properties of one or more source objects into a target object. The first argument is the target object, and subsequent arguments are the source objects.
    • const obj1 = { a: 1, b: 2 };
    • const obj2 = { c: 3, d: 4 };
    • const obj4 = Object.assign({ }, obj1, obj2);
    • console.log(obj4); // Output: { a: 1, b: 2, c: 3, d: 4 }
    • Object.keys(), Object.values(), and Object.entries():
    • Object.keys(): Returns an array of the object’s property names (keys).
    • Object.values(): Returns an array of the object’s property values.
    • Object.entries(): Returns an array of the object’s key-value pairs as arrays.
    • const person = { name: “John”, age: 30 };
    • console.log(Object.keys(person)); // Output: [“name”, “age”]
    • console.log(Object.values(person)); // Output: [“John”, 30]
    • console.log(Object.entries(person)); // Output: [[“name”, “John”], [“age”, 30]]
    • hasOwnProperty():
    • The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (not inherited).
    • const person = { name: “John” };
    • console.log(person.hasOwnProperty(“name”)); // Output: true
    • console.log(person.hasOwnProperty(“age”)); // Output: false

    Understanding object literals and how to manipulate objects is crucial for effective JavaScript programming. Object literals provide a flexible and readable way to create and work with complex data structures.

    JavaScript Array Methods: A Comprehensive Guide

    Arrays in JavaScript are special types of objects that are a data structure used to store multiple values. Array methods are built-in functions that can be used to manipulate arrays. There are many different array methods, but some of the most common and useful ones include push, pop, shift, unshift, slice, splice, concat, forEach, filter, map, and reduce.

    Here’s a discussion of array methods, drawing from the sources:

    • Creating Arrays:
    • Array Literal: An array can be created using bracket notation with values inside the brackets, such as =.
    • Array Constructor: An array can also be created using the array constructor by calling new array().
    • Basic Array Methods:
    • push(): Adds one or more elements to the end of an array. Modifies the original array.
    • pop(): Removes the last element from an array and returns that element. Modifies the original array.
    • shift(): Removes the first element from an array and returns that element. Modifies the original array.
    • unshift(): Adds one or more elements to the beginning of an array. Modifies the original array.
    • reverse(): Reverses the order of the elements in an array. Modifies the original array.
    • Methods to get information from an array:
    • includes(): Determines whether an array includes a certain value among its elements, returning true or false as appropriate.
    • indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.
    • Methods to extract a section of an array:
    • slice(): Returns a new array containing a portion of the original array. Takes two arguments: the starting index and the ending index (exclusive). The original array is not modified.
    • splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Takes two arguments: the starting index and the number of elements to remove. The original array is modified.
    • Methods to combine arrays
    • concat(): Returns a new array that is the result of merging two or more arrays. The original arrays are not modified.
    • Spread Operator: The spread operator (…) can also be used to concatenate arrays.
    • It can extract the items from both arrays and combine them.
    • Methods for looping through arrays:
    • forEach(): Executes a provided function once for each array element.
    • It does not create a new array or modify the original array.
    • It’s used to simply iterate through the array and perform an operation on each element.
    • High Order Array Methods:
    • These methods take a function as an argument (a callback function) and can be used to iterate through arrays and perform specific operations on each element.
    • filter(): Creates a new array with all elements that pass the test implemented by the provided function.
    • It returns a new array containing only the elements that satisfy the provided condition.
    • map(): Creates a new array with the results of calling a provided function on every element in the calling array.
    • It transforms each element of the array according to the provided function.
    • reduce(): Executes a reducer function (that you provide) on each element of the array, resulting in single output value.
    • It reduces the array to a single value by applying a function that accumulates the result.
    • It takes two arguments: an accumulator (previous value) and a current value.
    • Methods to flatten arrays:
    • flat(): Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
    • It flattens nested arrays into a single array.
    • Static Methods on Array Object:
    • Array.isArray(): Determines whether the passed value is an array.
    • Array.from(): Creates a new array from an array-like or iterable object.
    • Array.of(): Creates a new array from a set of arguments.

    It is worth noting that some array methods modify the original array, while others create and return a new array. It is important to be aware of this distinction when using array methods, as it can affect the behavior of your code.

    Modern JavaScript From The Beginning | First 12 Hours

    The Original Text

    hey what’s going on guys so I know you haven’t seen much of me lately I’ve been just really busy between my personal life and also working on courses and ideas for travestymedia.com which is my biggest Focus right now and I will be making videos soon but I wanted to give you guys kind of a little treat so this is the first 13 hours of my modern JavaScript from the beginning course which is a 37 hour course so it is only a portion but it’s packed with fundamentals and we go pretty deep into those fundamentals so things like data types control structures functions Loops the Dom so I really hope you enjoy it and if you do want to go further and you want to watch the other 20 plus hours I will have a link to the course in the description uh with a promo code so obviously this is geared more towards beginners but even if you’re already a JavaScript developer I can guarantee you that there’s there’s something you’ll learn all right so let’s get into it [Music] all right guys so I just want to quickly go over what JavaScript is and why you should use it so JavaScript is essentially the Java programming language as the name implies I’m kidding JavaScript has nothing to do with Java other than they share a similar name and they’re both programming languages so JavaScript is one of the core Technologies of the web alongside HTML which is a mock-up language and is used to structure web page content as well as CSS which is used to style that content so JavaScript is what brings life to the front end or the user interface of a website or a web app and it allows us to make web pages Dynamic not only that but it can also be used on the server side to do things like interact with databases and work with the file system and this is with the help of the node.js runtime so JavaScript is a high level interpreted programming language used to create interactive and dynamic website experiences and when I say interpreted what I mean is that it’s executed line by line rather than being compiled into machine code first so the code is executed on the Fly making it a scripting language hence the name JavaScript so as far as what JavaScript is used for I wouldn’t be able to fit everything on this page so I’m going to go over just the general things that JavaScript is used for so first off it’s used to manipulate the Dom or the document object model and I’ll be going over the Dom in depth but you can basically think of it as a tree-like structure of nodes and everything on the page is a node including every HTML tag every attribute every piece of text and so on so JavaScript provides methods for dynamically changing that structure or changing the content or the styles of the elements in the Dom for example you can use JavaScript to add remove or change text of a heading or the content of a div or the styles of an element such as its color font and size so this is an important aspect of JavaScript as it allows developers to create Dynamic and interactive web pages that can respond to user actions now those user actions are called events and JavaScript gives us a way to handle events so we can respond to things like Mouse clicks or drags or hovers keyboard events form submissions and just about anything you can think of that you can do in the browser window and again this allows us to create very Dynamic interfaces and things like modals or drop downs collapsible content and so on so making asynchronous request is one of the most powerful uses of JavaScript and it’s used to interact with back-end servers whether it’s your own server that you created or a public API such as the GitHub or YouTube API so we can make HTTP requests right from our code to fetch data or submit data and this happens all behind the scenes without having to refresh the page and this is often used in what are called single page applications or Spas to dynamically load and update content without having to reload the entire page so as far as animations and effects there’s many different ways that we can create these using JavaScript we can use CSS Transitions and animations with JavaScript there’s the request animation frame method there’s different libraries like animate.css and gsap so these methods allow developers to create a wide range a wide range of animations such as fading moving elements along a path scaling rotating and so on now data manipulation which is the process of modifying or transforming data can be done with JavaScript because it’s a full-featured language with data structures like arrays and this allows us to sort filter and aggregate data so there’s all kinds of powerful array methods that we can use such as map filter reduce and we’re going to get into all of these later on so JavaScript can also be used to store data on the client or in the browser using things like local storage session storage and cookies we can also create single page applications or spas and these are applications that load a single HTML page and dynamically update the content without having to reload the entire page and this provides a really seamless and responsive user experience so no page reloading we can create different routes and so on and usually you would use a front-end framework for building Spas so you’d use something like react or view or angular but you can also create them with vanilla JavaScript now everything that I’ve said up until this point is all client-side or front-end JavaScript and that’s where it is used the most I would say but you can also use it on the server side with the node.js runtime as well as Dino so in addition to consuming apis from the front end we can also create apis that interact with databases on the back end and there’s a ton of Frameworks that you can use to help you with this including Express which is extremely popular and we’ll actually be creating a backend API with Express later on so the last thing I want to go over are some reasons why you should learn JavaScript so one is popularity JavaScript is one of the most widely used programming languages with millions of developers using it to build websites web applications browser-based games server-side apis and more so it makes it a very valuable skill to have and it opens up many job opportunities and allows for collaboration with other Developers so it’s also very versatile um it’s used like I said on both on the front end and back end of web development making it a full stack language this versatility allows developers to build complete web applications using only JavaScript not only that but there’s Technologies like react native which allow you to build complex mobile applications and Technologies like electron which allow you to even create desktop applications some of the most popular desktop apps are actually built on JavaScript and electron including vs code which is the text editor that we’ll be using as well as Postman which is the HTTP client that we’ll be using so I would say that JavaScript is relatively easy relative being the key term so if you compare it to other languages especially more low-level compile languages like C and C plus plus it’s much easier to get into and I think anyone who has a passion for coding can learn JavaScript and you don’t have to be some genius you don’t have to be great at math or anything like that you just have to have some drive and the willingness to learn and put the effort in so JavaScript also has a very very large and active Community which provides a wealth of resources support tutorials and tools for Learning and improving your skills from websites like stack Overflow to social media JavaScript just has a huge reach and when it comes to tools like actual development tools there’s just there’s so much open source software so you have npm which is the node package manager with I think it’s like 1.3 million packages that you can just download install and use so there’s just there’s there’s no shortage of resources or tools when it comes to JavaScript all right guys so in this video I want to go over the tools we’ll be using as well as our environment which is going to be very simple we’re writing vanilla front-end JavaScript so essentially all you need is a text editor and a browser but I do want to show you some of the extensions that I’ll be using and so on so as far as a text editor you can use whatever you want you probably already have a preference I’m going to be using visual studio code that’s what I recommend it’s very easy to use it’s intuitive it has great extensions and it’s very popular I would say the most popular for web development especially front-end web development and then there’s some extensions I’ll be using as well so I would suggest using it but you don’t have to if you use Sublime Text or atom or something else you can still follow along just fine so the next thing I’d say to install is git if you don’t have that already and git is Version Control so basically we can create repositories with our code and we can also push to third-party services like GitHub or git lab or bitbucket so this is not a git course but I will show you just the basics and we will need to push to a a service so that we can host some of our applications some of our projects because I do want to do a couple simple deployments all right and you can install get many different ways if you’re on Mac you can use Homebrew you can also go to get Dash scm.com and you can download and install it as well and then I’d also say install node.js just to have it on your system node.js is a it’s a JavaScript runtime so it essentially allows you to run JavaScript on your machine or on a server rather than just in the browser so you can actually use node.js as your your backend technology now this of course is not a node.js course but there are some things that I’d like to talk about especially with npm which is the node package manager and that comes with node.js so I would suggest installing that and you can install either the long-term support or the cut the most recent the the current version really doesn’t matter for this course so what I want to do now is just go into vs code and just show you the extensions that I’m using now I have a ton installed but the there’s really only two that I would highly recommend that you use with this course so one is called live server so if we scroll down here see right here live server so we we are we’re writing front-end JavaScript so we don’t really need any kind of server you could have an HTML file right on your desktop and have a Javascript file linked to it or just create the script tag in the HTML file and just open it run it in a browser and it works however live server gives you like a mini Dev server that you can run your uh your files with and it’ll Auto reload in the browser whenever you make any changes and that that includes making changes in the JavaScript the HTML the CSS if you change any of that code it auto reloads so you don’t have to keep reloading the browser yourself so I would definitely recommend using this that’s what I’ll be using throughout the course and then the other thing that I would suggest is prettier which is a code formatter it just keeps your your code nice and clean in fact I’m going to bring over a file real quick and you guys of course don’t have to do this but I’m just going to open this up it’s a file from from the course and I’m going to show you my settings in a minute but basically you’ll see if I tab a line way over here and then I go when I save it’ll put it right back okay so it keeps your your code nice and clean and then you can also set like the the spacing you can set if you want to use semicolons or not because in JavaScript semicolons actually are not you know they’re not mandatory so you can set those to on or off as you can see I have them set to on so if I miss a semicolon and I save it adds it automatically and you can also set it the other way around where if you have a semicolon and you save it gets rid of it and then the other thing that I want to show you are quotes so you can see this string is wrapped in single quotes I prefer to use single quotes so I have it set so that if I do if I have double quotes in here and then I save it automatically gets set to single quotes all right now where you can configure this stuff once you install prettier is if you go to the settings so right here settings and then just search for prettier and then you’ll find all these these options here but the ones I want to show you are right here so semi you can see I have this checked so it’s going to add semicolons if I forget if I uncheck it it’ll do the opposite and then down here I have single quote checked which by default I believe this is not checked but I prefer a single quotes So I do have it selected and then here my tab width I believe the default is four but I have mine set to two which makes it a little more Compact and neater in my opinion all right so those are the settings now to make sure that your code formats when you save just search for a format in the settings and right here format on Save just make sure that that’s checked all right so we can close that up close that but that’s it as far as the tools that I’m using and our environment so let’s move on to the next video okay so most of the code that we write is going to be within a JavaScript sandbox which is just a bunch of files and folders that are going to pertain to each section of the course but before we do that I just want to show you the very basics of just creating an HTML and a Javascript file and running the JavaScript in the browser Etc and for those of you that you know aren’t are pure beginners just kind of bear with me because I do want this course to be for everybody even if they’re just just starting out with JavaScript so you can skip some of these videos if you want or just you know watch them as a refresher so I’m just going to create a folder so go ahead and create a folder wherever you want I’m going to create it on my desktop and I’m just going to call it I’ll call it my Dash website again I’m going to delete this after so it doesn’t matter now you want to open the folder with your text editor and there’s multiple ways to do that you can open the text editor and you can open the folder from there or you can usually on Windows you can usually right click and if you’re using vs code you’ll see an option to open with code so you can go ahead and do that if you’re using Sublime text you I think you also have a context item if you’re on a Mac what you can do is drag the folder down to the vs code icon or whatever you’re using and it will open it up and you can see on the side here is our my website site folder so from here I’m going to create a new file just click this icon and let’s say index.html so now we have an HTML file and with vs code we have a tool called emit which is really great for for writing quick HTML and CSS so for instance I could do H1 enter gives me an H1 tag if I want to add a class I could say like my class so dot my class enter or Tab and then if I wanted an ID I could do you know my ID enter our Tab and let’s say I wanted like five each ones I could do times five there’s all types of stuff you can do so I do have a YouTube video on Emmett if you’re interested but another thing emit allows us to do is just create a kind of a boilerplate for our HTML so I’m just going to hit exclamation enter and you can see it gives us our head body tags Etc and again if I know a lot of you guys already know this most of you probably do but just bear with me so if I just hit tab a couple times I can go to the title and just change it to let’s say my website and then in the body for now I’m just going to put in H1 and then hello world and save that okay now since this is an HTML file I can just open it like I can just click on it make sure it opens with a browser and we’ll be able to see the hello world so you can just develop like this if you want for this course like I’m just going to make this smaller so if we change something like let’s say we put an exclamation here and I save obviously since I just opened it on my file system not on any kind of server I go over here and I have to reload now I don’t want to have to do that for everything so that’s where live server comes in so what we can do as long as you have it installed just search for live server so right here and get that installed and then you’ll see this go live button down here you could click that or you could right click and just say open with live server and what it’ll do is open up another Tab and you can see in the URL bar it’s this is our Local Host this is one two seven zero zero one that’s called our loopback address and it runs on Port 5500 by default now if I were to change something like let’s say get rid of this exclamation and save you’ll see it auto updates or Auto reloads in the browser so I don’t have to keep reloading and that and that is with HTML CSS and JavaScript now I expect that you guys know HTML you should know at least the basics of CSS so I’m not going to really get into that to start to write JavaScript there’s a couple ways we can do it one it one way is not really recommended but I’m going to show you it anyway and that is to just write it directly in the HTML so to do that what you would do is go down right above the ending body tag and create a script tag which is an HTML tag and then anything we write in here is gonna is gonna run as our JavaScript so for instance we could do alert which is just it’s a function that’s on the window object and I’m going to talk about that in a little bit and we can pass in here let’s put a string so we need our quotes and again I’m going to talk about data types and all that very soon but I’m just going to do a Hello and save and you’ll see that that’s going to automatically run because we are using live server so since the file changed the website reloaded and now received seeing this alert of hello all right now typically you’re not going to do this you’re not going to write your JavaScript directly in your HTML it’s just bad practice you want to have your JavaScript separate okay this is called inline JavaScript just like with your CSS you normally wouldn’t write your CSS in your HTML you’d create a separate file so let’s create a new file and you can call it whatever I like to use script JS for just general JavaScript files and this will show us our alert again because the the page reloaded and then in here let’s write something else we’ll do an alert and let’s say hello from the JS file now if I save this we’re still just seeing the hello that’s in the index.html because we haven’t specified that we actually want this file to run so to do that we’ll come over here let’s get rid of the inline JavaScript but we’re going to keep the script tags now to load this script.js file we can just add a source attribute much like you would do with an image tag so let’s just say script.js it’s in the same folder you might have it in a JavaScript folder or JS folder like that but ours is right there so we’ll go ahead and save and now we’re going to see this hello from JS file okay so that Javascript file is now being loaded very very very simple stuff I know ninety percent of you probably already know this but of course I need to think of people of all skill levels okay so what I’m going to do now is stop live server and you can do that by hitting this button right here you can also right click and say stop live server and now if I reload this it’s not going to work anymore okay so I’m going to close vs code and I’m just going to delete this this uh my website folder and then in the next video we’re going to start to learn about the console in the browser which is extremely important and we’re going to start working on our Java in our JavaScript sandbox all right guys so before we start learning JavaScript I just want to quickly talk about the JavaScript sandbox when I do a course I don’t like to just type out the code and and that’s that I want you guys to have uh Resources with all the code in the course so what I do is create something called The Sandbox which has a folder for each section and in each section folder you have a folder for each video with that code okay so as you can see I’m just starting out here so I have my variables and data type section with the first video which is going to be about the console and then in that is just an index.html which right now is empty and a script JS which is empty okay now for the most part most of the learning modules that aren’t part of a project in the beginning are only going to need these two files so you don’t have to use the sandbox you can create your own files now in the downloads for this video you will have the finished version of the sandbox which of course is all the finished JavaScript and then you’ll have a starter version which is going to be pretty much everything but the JavaScript you’ll have all the files and folders you’ll have the HTML any CSS if we used any CSS but the JavaScript will be empty and if you want to use that starter package you can or like I said you can create your own so right now what I’m going to do in this this console folder is just create a boilerplate so I’ll just do exclamation and I’m just going to put console in the title and I’m not going to create this in every video I’m just showing you just just for the beginning and then since we’re not dealing with you know the Dom or anything yet I’ll just have an H1 in here that says oh we’ll put the name of the say console the name of the video and then we just want to add a script tag we can do script colon SRC and we want to link in our script JS okay so essentially at the beginning all of all the videos will start like this in the HTML and then we’ll proceed in our JavaScript now one thing I want to mention is if you’re creating folders like if you create a folder inside of an empty folder by default it’s going to be compact so it’s going to be like data type slash and then zero one console now I don’t like that because it can be kind of confusing which you know to know which folder you’re in so if you want to disable that you can just click on settings so we’ll go to settings microphones in my way and then just search for compact and then right here compact folders I have it unchecked but if I check it you’ll see it goes in this this horizontal fashion which I don’t like so you can just uncheck that if you want all right so now that we have this set up I’m just going to open this index.html with live server and we have our script connected so we don’t even need that HTML anymore and we’ll just make this a little smaller and now in the next video we’ll start to look at the JavaScript console all right guys in this video I want to go over the console in the browser because this is something that we’ll be using throughout the entire course and you’ll be using throughout your entire career as a front end or full stack web developer now every browser no matter which browser it is I’m using Chrome they all have what are called developer tools or Dev tools and in Chrome you can go to the menu and you can go to more tools and then developer tools or you can on Windows I believe it’s F12 you can toggle the dev tools and then on a Mac you can do command option I now you’ll see there’s a bunch of tabs here you’re probably familiar with the elements tab where you can you know highlight elements you can see the CSS you can even edit uh page elements of course this is only on my machine if I reload it goes back but you can do a lot with the elements tab but that’s for HTML CSS the console is where we’ll see all of our front-end JavaScript warnings and errors and we can log things to the console that’s what I want to get into in this video now you can also go directly to the console with command or control I think on Windows it’s can it’s Control Alt J I know on Mac it’s command option J and that will open it’ll go right to the console now as I mentioned this is where you’re going to see your your warnings and errors for example if I go into my script here and I just put in an A and I save that and it runs we’re going to see this reference error it says a is not defined shows me the line number and the file where it’s coming from all right so very helpful with con with uh warnings and errors and of course we can log to the console from our script which I’ll show you in a second but we can also type JavaScript right in here so if I wanted to do an alert I could execute that and you’ll see that well we get this alert with one now we’re going to see undefined on the next line because what this is is if there’s a result of the expression then it will be put here and there’s no result to alert we’re just running an alert function if I were to do let’s say one plus one then it’s going to show me two all right I can also set variables so let’s say I wanted to set x to the value of 100 and and we’ll go over variables and data types and all that but I can do that here as well I get undefined because nothing there’s no result to that if I were to do let’s say X plus 10 then we’re going to get 110 because X is equal to 100 okay I could use the date function if I wanted to to get the date so there’s there’s all types of stuff we can do here but you’re not going to do that very often maybe to do some testing and you know see if something is available on a Dom element or something like that but it’s not too often you’ll type JavaScript in here now to clear your console there’s a few things you can do you can use the clear function so clear with some parentheses and that’ll clear it also you can do command or control L that’ll clear it up as well or you can just reload the page all right so I’m gonna come over here into my script and I’m going to show you how we can log to the console uh in a couple different ways now we do this with the console object in fact if we go over here and we type console in the console and hit enter we’re going to see the console object now objects are common in in just about every programming language and you can think of them as they’re an entity that have properties and methods a property is like an attribute or a value where a method is a function something that does something and you can see that these are actually all methods they have an F next to them they’re functions and functions are executed with parentheses and don’t worry if you don’t understand that we’ll get into functions in a little bit now there’s quite a bit here but don’t let that overwhelm you because you’re only going to use maybe five percent of these most of the time you’re going to be using console log or console.log so let’s come over to to our script I’m actually going to reload the page just to clear that up and let’s look at console.log now what this is is console is is an object and remember an object has properties and methods a method is a function so log is the method that I’m using and to execute a function or a method you have to use parentheses so I’m executing the log method that’s on the console object and we use this dot syntax in JavaScript to access properties and methods okay now we want to log something so in here in the method or in the function we want to pass in an argument so I’m going to pass in a number let’s say 100 and if I save that and it runs you’ll see that now in the console we’re seeing 100. now any piece of data in JavaScript or really in any programming language has a type and this is the type of number and I’m going to go over the data types in the video after the next one so let’s say we want to log a different type like a string so a string is just a string of characters so a string has to be wrapped in either double quotes or single quotes so I’ll just say hello world and I’ll save that and you’ll see that will log the string and notice they’re different colors so the number is purple the string is white now if you want to log more than one thing at the same time you can do that as well so let’s say we want to log a number we’ll say 20 and then a string and then let’s say a Boolean which is a true or false so if I go ahead and save that you’ll see that it’ll log those three things those three values now in in many cases or I’d say most cases you’re going to be logging variables or results to functions it’s not that often you’ll log straight strings like that unless it’s like it worked or something if you’re running a function or something like that and you want to see if it worked so let’s just create a variable and we’ll get into variables more soon but if I just set let’s say x to the value of 100 then I can come down here and console.log x and of course that’s going to give me 100. all right now there is another extension that I I don’t think I mentioned and that is let’s see where is it right here JavaScript es6 code Snippets and it just gives you some some convenient Snippets and one of which um that I use quite a bit is CLG so if I do CLG enter it gives me a console log so I’ll use that quite a bit there’s also some other ones I use like try catch you can do if statements you know and I don’t usually use it for like if statements and stuff but you will see me do CLG and maybe a few others now in addition to log we also have console.error so I’ll say just alert and that’ll log to the console but you can see it has this red background red border and it also shows you the scope so I mean it’s up to you if you want to use it I I typically don’t I usually use console.log for everything but remember the console is for the developer this isn’t for the user users don’t come to your website and open up the console now in addition to alert we also have con console.warn so I’ll just say warning save that you’ll see we get the the yellow background pretty much the same thing just a different color and then we can also do tables for objects so I’m going to do console.table and I know we haven’t gone over objects yet but there are object literals I should say which are key value Pairs and they’re wrapped in curly braces so I’ll just do a simple object with a name as the key Brad is the value and then email as the next key and then Brad at Gmail for the value and if I save it you’ll see this object is printed out as a table which is kind of nice and it also shows it as the object next one is groups so we can do console.group and give that group a name let’s call it simple and then we can add some let’s just take we’ll just take these three here and put those right underneath and then we want to end the group so we can say console dot group end and if I save that we check it out you’ll see that we have this simple with the this this collapsible arrow and the warning the alert and the log are now under that in that group all right now this isn’t really this isn’t something that I use but I just want you guys to know that this stuff is available you’ll probably only end up using console log 95 of the time but again I do want you to know some of the stuff that that’s available on this console object now another thing that we can do that’s kind of cool you probably won’t use it much but I do want to show it to you is adding CSS styles to your console logs so what we can do is is create a variable I’ll call it Styles and I’m assuming that you guys know CSS but we can put some Styles in here like let’s say padding 10 pixels we’ll say let’s do background Dash color and we’ll do white and then let’s do the color the text color which will be green okay so we just have a variable with some CSS now what we can do is a console log and I’ll put a string in here of hello world and the way that we apply the Styles is at the beginning of the string we can add a percent C and then as a second parameter we can pass in our Styles now if I save that and run it you’ll see down here we get the string of hello world with the CSS Styles applied now there are some other methods on the console object but I don’t want to spend too much time on stuff you’re probably never going to use so in the next video we’re going to look at code commenting we’re also going to talk about some of the helpful keyboard shortcuts that you can use while writing code all right guys so in this video I want to talk about commenting and also give you some helpful shortcuts to use while you’re coding now as far as the the code here it’s the same exact stuff that we did in the last video we’re not actually going to write any code in this video aside from comments but I am going to show you how to kind of navigate around and use some keyboard shortcuts Now comments are used for documenting your code and explaining things in a more human readable way oftentimes multiple developers work on the same code base and comments are used to explain what a certain piece of code does it’s especially important when you’re working on a project with a team of developers and comments are also used to disable code so if you have code that you don’t want to delete but you also don’t want to run then you would comment that block of code out you can even use commenting as like a to-do list for for yourself or for other developers so very helpful and commenting in JavaScript is very simple so I’m just going to go up to the top here and we can just add double forward slashes and this is a single line of code so say this is a single line of code if I go on to the next line and start typing you’ll see it’s not commented all right now in vs code and in most text editors if you just hit command or control and then forward slash it’ll put the double forward slash for you you can toggle it all right also if you want to comment out a line of code that’s already there like let’s say this one you can go anywhere on the line and just hit command or control forward slash and you can toggle it you know put it into a comment and toggle it so if you want to toggle multiple lines of code there’s a few ways you can do it what I would probably do what I usually do is go to either the beginning or the end hold shift and hit up or down depending on what which code I want to highlight and then I’ll go ahead and do command or control forward slash and it will comment all those lines out but when you do that every line has a comment on it there’s another way to add multi-line comments and that’s with the forward slash and asterisk and then you want to go to wherever you want the comment to end and put an asterisk forward slash so now you can see everything that’s in between that is is commented out in fact I’m just going to put right here we’ll say multi multi-line comment okay so those those are the two ways of commenting in JavaScript now as far as keyboard shortcuts I already showed you that if you hold shift you can go up or down and you can highlight code you can also hold shift and go right or left and highlight as well if you want to navigate a line of code I’m just going to go to this one actually let’s go to this this table right here so if we go to this table and I hold down command or control and I hit right now the right arrow it’s going to go all the way over to the end of the line if I hit left it’ll go to the beginning of the line okay now if you want to go in between and you don’t want to navigate every single character you just hold option or alt on Windows and you can see it’ll go from this console to the end the beginning of console to the end if I hit right again it goes to the end of table hit right again it goes to the beginning of the object and so on okay so it’s just a faster way to navigate across now you can also hold down shift and if you do option or alt right or left it’ll just highlight it’ll go across faster and you can highlight while you’re doing that and you can also hold shift and hold down command or control and you can highlight from where you are over either right or left okay now if you want to move a line of code up or down you can hold alt on Windows or option on a Mac and you’ll see this console.table I’m just moving it up and down the file okay that’s holding option or alt if you want to duplicate it then you could hold shift option or shift alt and hit the down arrow and you’ll see I’m just copying the the line of code down and of course undo is is a command or control Z all right now let’s see if you want to let’s say I want every instance of this log right here so I’m going to hold shift and just highlight it and then in vs code it’ll automatically highlight each one now if you want to a little it’s not actually highlighting it like with your cursor it’s just visually if you want to actually highlight with your cursor I can hold I can hit command or control D and you’ll see it selects the next DOT log if I hit command or control D again it selects the next one and I can edit those I’m editing you know all of the dot all the logs okay now if you want to select all of them instead of going one by one with command or control D you can do shift what is it command shift L will will highlight them all and you’ll see now I got all the dot logs and I can edit them all right you can also place your cursor so if I want to put my cursor at the beginning of the the log here I can hold either alt on Windows or option on a Mac and I can just click there click here and click here and then I can type in all where all the cursors are okay so you’re not going to remember these right now so don’t worry you know when you move to the next video and you forget all of these don’t worry about it use use one or two you know while you’re coding even in this course use one or two and learn them so that it kind of becomes second nature and then choose another one or two and start to use that you know and before you know it you’ll you’ll just do it without even thinking all right and then a couple others I wanted to show you if you do command shift o you can search for a file so if we do like index you’ll see that both of our index htmls if I do script you can see our script js’s and you can switch to those as well all right if you want to search you can do let’s see you can do command option f and if I want to look for you know console it’ll show me all those you can also do command shift F and you can search over here for um we’ll say console and it will show us all where console is in every file not just the file that we’re in all right and you can also just click on search here as well and if in vs code if you want to toggle the sidebar you can do command B so our control B that’ll just toggle the sidebar uh what else if you want to toggle the terminal you can do command or actually it’s control till day so I can toggle the terminal down here which we’re not going to get into maybe maybe we will later on in the course but yeah so those are the kind of the the most common shortcuts that at least at least that I use so hopefully that helps and in the next video we’re going to start to look more at variables so in this video we’re going to start to look at variables and variable declarations now variables are basically containers for pieces of data and that data can be one of many different types and it’s important to understand the different data types in JavaScript so we’re going to go over that in the next video now when we declare a variable we need to use one of three keywords so let’s just say ways to declare a variable so basically we have VAR let’s make sure we comment this out so we have VAR we have let and we have const okay so these are the three ways that you’ll see variables declared in JavaScript now you probably won’t see VAR very much anymore VAR was the original declaration but in es2015 which is the 2015 update of JavaScript or ecmascript also known as es6 it was a huge update to the language and they introduced let and const and the main reason for that is due to something called scope and I’m not going to get too much into scope right now because it’ll go over a lot of people’s heads that are just getting started we’re going to have a whole section on function scope execution context and stuff like that but for now just know that when you write code in just right in the file not inside of a function not inside of an if statement that’s the global scope all right now in the global scope VAR and let work in a very similar way now const is a little different because it’s for constants it’s for values that you that are not going to be reassigned at a later time okay and I’ll get I’ll I’ll show you const in a few minutes but let’s start by just creating some variables here I’m going to say first name and let’s set that to a string so we do need quotes so we’ll say John now notice I made this n capital so the basically the beginning of the second word I capitalize I’ll talk about that and some other ways you can format your variables in a few minutes but let’s say first name we’ll say last name and set that to do okay so we’re just creating some strings putting them into some variables and we’ll do a console log of first name and we can log more than one thing so we’ll do that here as well and you’ll see we get John Doe okay and if I wanted to create a variable with another data type like a number we could say let age equals 30. we can console log age okay now if I try to log age up here you’ll see that I’m going to get an error it says cannot access age before initialization when we do this right here let cons VAR this is initializing a variable okay and you want to initialize it before you use it now it does act a little different if we use VAR so if I say VAR here and I run this we don’t get an error but you’ll see that it is undefined and this is due to something called hoisting which is a little more advanced and we’ll we’ll talk about that in at a later time but yeah you want to initialize your variables first I’m just going to get rid of that now when it comes to naming your variables there’s a couple conventions that we need to follow so variable names can only be letters numbers underscores and dollar signs okay so you can’t have anything else you can’t have like a plus symbol or an asterisk or anything like that and even though that you can have numbers they can’t start with a number so if I were to say like let one name equals Brad that’s not going to work I’m going to get an error but if I move that one to the end here then that’s fine but if I try to add like a plus sign or something like that that’s not gonna that’s not gonna work okay now as far as the formatting of your variables for like multiple words just paste this in here what I did here with first name and last name this is called camel case where you start with a lowercase number for the first word and then every other word after that is uppercase okay so that’s camel case and that’s usually what you’re going to see now you have other ways to do it like you could use underscores to separate The Words which I don’t particularly like but I mean it is it’s all right I guess you see a lot of that in PHP and then we also have Pascal case where the the first word is also uppercase and there are conventions or there are certain times where this is the convention such as in react components or most front-end Frameworks when you create a component the file name is Pascal case so is the class or the function name of the component and then you might see all lower case which I really don’t like I don’t think that it’s very readable especially if you’re getting into like three and four words okay so let’s look at reassigning variables so we’ll say reassigning variables now we have a variable up here of age you we use let we set age to 30. so if I come down here I can then take age and then I can reassign it to let’s say 31 let’s say John had a birthday and then we’ll just console log age again and now it’s 31. all right now another thing I can do with let is just simply declare it and not actually assign a value so let’s say we want a variable called score but that’s it I’m just going to declare it okay I’m allowed to do that I don’t get any error and then I could take score and maybe add 1 to it let’s do a console log of score and we get 1 and then we might have like some kind of if statement I’ll just put true in here so that this runs and and don’t worry if you don’t understand this but let’s say we had we have something happen where the score and gets added one again we’ll say it equals score plus one and then down here we’ll console log again score and now we get two okay so that’s something that is very common using let now let’s try the kind of the same thing with const so we’ll go ahead and say const and I’ll just I’ll just call this X and I’m going to set that to 100 and then let’s say I want to take that X variable and then reassign it to 200. if I save that I’m going to get an error it says assignment to constant variable a type error okay so a constant cannot be directly reassigned like this another thing you can’t do with const is just declare it and not initialize so for instance if I were to say I already have score so I’ll say score one if I were to just do this you’ll see it’s already giving me an error here const declarations must be initialized if I save I’m going to see the same same error here okay If This Were A let though that I can do that okay so just know that const can’t be directly reassigned now where a lot of people get confused is when you’re using arrays or objects things that are not primitive values and I know I haven’t gotten into that stuff yet but I just want to show you a quick example that’s pretty easy to understand so if I use const and I have an array right and and an array is just multiple values so let’s say one two three four all right what I can’t do is directly reassign by taking array and saying well let’s do one two three four five if I do that I’m going to get an error because I’m using the equal sign directly reassigning but what I could do is with a raise you have a bunch of methods such as push and pushes is a method that will add on to the end so what I could do is say array dot push five and then if I console log my array that works so I manipulated this array I changed it to from one two three four to one two three four five by simply using a method to push five onto the end okay and then the same goes with objects if I say cons person and I set that to an object and I say name Brad and then we’ll come down here now if I were to just take person and directly reassignment you guys know that’s not going to work but I could do person.name and set that equal to John and that works because I’m not I’m not directly changing the variable I’m changing a property or a key inside the variable or not a key but a value of a key okay I could also do like person dot email and I could add on let’s say Brad at gmail okay and then if I do a console log of the entire person object you’ll see I have name John and email Brad Okay so when people ask me you know what should I use cons let or both or whatever I say it’s it’s it’s really preference now for me I always use const unless I know I’m going to directly reassign something like like this right here okay um now you’re gonna find that you don’t do this very often okay I shouldn’t say that I don’t do this very often we use a lot of the times we use objects and arrays and using Cons with that is just fine because there’s not too many you know you don’t directly reassign this very often you’re going to do stuff like this you’re going to use methods you know you’re going to assign properties and stuff like that so that’s my rules I always use cost unless I know it’s something that I’m going to change such as a score and a game you know you might add to that but you probably or what I would do is have it in an object and then just change that value so I could use const in that case so I mean you’re going to find a lot of this stuff is preference all right now another thing that I just wanted to mention is we can declare multiple let’s say multiple values at once or multiple variables so I’ll just go ahead and say actually let’s use let here let’s say let and I’ll say ABC so I could do that right I don’t even have to assign it because I’m using let and then I could also do like const I can’t just I have to assign it but I still can do multiple at once so I could say like a I can’t do a because I just used it up there but let’s say d equals 10 I could put a comma and say E equals 20 and let’s say f equals 30. okay and all of that is just fine so if I console log d down here you’re going to see we get 10. now I usually don’t do this I’ll just use a semicolon and then just do const d const d const f I just think it looks cleaner but that’s just again that’s just preference but you can assign you know multiple at the same time and if you don’t actually assign a value and you log it what we’re going to get is undefined okay which is one of the data types which is what we’re going to talk about in the next video all right guys so I want to spend a little bit of time on data types so when you’re dealing with code any any type of code any language and you’re dealing with data that data is associated with some kind of data type okay and it doesn’t matter which language you’re using they all have some kind of data types and they can be different language by language now in JavaScript you essentially have two types of types you have primitive data types and you have reference types or objects and I’ll talk about those in a second but I want to start off with primitive data types now I feel like a lot of JavaScript courses kind of skip over some important fundamentals and what I want to do is I’ll talk more about this in the next video but I want you to understand how these data types are stored and how primitive data types are different or are accessed differently than reference types but again I’ll talk more about that in the next video right now I just want you to know what these types are so the first is a string which we’ve dealt with so a string is essentially a sequence of characters and a string must be enclosed in either double quotes or single quotes or back ticks next we have a number which are integers which could be positive or negative numbers as well as floating Point numbers or decimals now in some languages you actually have either a decimal and or a float type in JavaScript we don’t what if it’s a integer or if it’s a decimal or floating Point number it’s they’re all the same they’re all going to be then the type of number okay so keep that in mind next we have a Boolean which represents a logical entity it can be either true or false next we have null which is the intentional absence of any object value and a lot of people get null confused with undefined which I’ll talk about next but just know that null is it’s always it’s intentional it’s supposed to be there but it’s supposed to be null it’s supposed to be empty you can essentially think of it as empty now the next one undefined is a variable that hasn’t been defined or assigned okay so null is purposeful undefined usually isn’t all right next we have a symbol which I’m not going to talk too much about right now because it’s it’s kind of advanced and and it was actually added in es2015 or es6 so a symbol is essentially a built-in object whose Constructor returns a sim a unique symbol or a symbol that is unique all right and and we’ll get into that later it’s not something you use very often at least I don’t and then the last one is a new data type that was just recently added called Big int okay and it just represents really really big integers really large numbers that the number type can’t handle all right and we will jump into some code in this video and just kind of show you how to how to store each of these in a variable so the next type of type is reference or objects now reference are objects they’re non-primitive and when we assign a reference type to a variable the variable is given a reference to that value and again I’m going to talk more about how reference types and primitive types are stored and accessed in the next video but object literals arrays functions these are all examples of reference types now in programming you have something called Static typing or statically typed and you have dynamically typed JavaScript is a dynamically typed language and what this means is that we don’t explicitly Define the types for our variables so if I say like const name equals Brad I don’t have to put const name String equals Brad it just knows it’s Dynamic with many languages you actually have to you have to add the types yourself those are statically typed languages like C C plus plus Java and I’m sure that some of you have worked with some of those languages in JavaScript you don’t explicitly set your types however there is something called typescript which is very very popular and it’s a superset of JavaScript meaning that it’s everything that JavaScript is it essentially is Javascript but it also has some additional features including static typing okay so there are reason to use static typing it is more code that you have to type but it can make your code more verbose and it can make it less prone to errors and a lot of people really love typescript so that might be something you want to look into once you really learn the fundamentals of JavaScript okay so I just want to jump into vs code and go over these types in the text editor and also show you how we can get the types of a specific variable so let’s start off with strings which are very simple just they’re just sequences of of characters so I’ll create a variable and I’m using const like I said in the last video I use cons for everything unless I know I’m I’m going to reassign it so we’ll say first name and we’ll set that to Sarah alright now I want to console log out the value so we’ll say first name but I also want to show you how we can get the actual type from this first name variable so as a second argument I’m going to pass in the type of operator okay so just type of and then a space and then whatever you want to get the type of sole first name and now you’ll see it’s logging out Sarah and string all right now there’s going to be a few variables that I want to show the value and the type and I don’t want to type it twice so I’m going to create another variable here we’ll just call it output and for now I’ll set it to first name and then let’s come down here and and put output now I just want to mention some little little tips and tricks as we go along I already went over some shortcuts but just to kind of remind you we can go to the the end of this first name hold shift and then highlight it and then we can do a command or control D to select the next instance of first name and then replace it with output and then save okay and we should get the same result so I’ll just mention little tips and tricks like that as we go along so the next type I want to look at is number so let’s do const we’ll say age equals 30. so that’s an example of a number if I change that to age we get 30 and it shows number from our type of operator now I also want to mention that decimals so if I do temp and set that to let’s say 98.9 and then we look at the type for that that’s also going to be a number there’s no specific float or decimal or anything like that everything is a number in JavaScript so the next type is Boolean which is really simple it’s just a true false value so maybe we want to say like has kids since we’re talking about a person and we’ll set that to true and then we’ll come down here we’ll change the output to has kids and we get true when it says Boolean so the next one is no which is basically like an intentional empty value so maybe we have like an apartment number but let’s say this person lives in a house so we set that to null there’s no apartment number there’s no need for one and this one is a little weird because if we set this to apartment number and we look at the value which is null and then we look at the the result of this type of we get object okay now this is a little confusing because null is not an object it’s not a reference type It’s A Primitive but there’s a reason for this it’s kind of in summary it’s kind of a mistake in fact I’m going to paste in the um the link right here if you’re interested and we can check it out real quick so let’s go to that link and it just kind of explains why this happens uh and it has to do with the first implementation of JavaScript values were represented as a type tag and value the type tag for object was Zero null is represented as the null pointer which was 0 x 0 0 consequently null had zero as a type tag hence the type of Return of object so in case you’re wondering why it says object and not null that’s why but it’s not it’s not that important honestly now the next is undefined and you’re probably not going to purposely set variables to undefined very much but just to show you if we were to do remember in the last video I showed you we can we can use let to just create a variable but not actually Define it to something so I’ll just say let’s score and then we’ll pass that in here to Output so we can see the value in the type and both are undefined the value and the type okay so if you just set a variable and you don’t Define it it’s going to be undefined now you can also explicitly set it to undefined you don’t do this very much but I could say cons score let’s just comment this out and I could just say set it to undefined and we get the same thing all right now a symbol is A Primitive type but it’s not something that you’re probably going to use very much especially in in you know your early career but just to show you we can create let’s say ID and let’s set that to a symbol so we’re going to say symbol with parentheses and then pass in a unique identifier of ID and then we’ll change this to ID and save and you’ll see we get symbol as our type and then the last one is although I should say the last primitive type is Big int which is just a really big number that is too big for the number type so I’ll say const n and I’m actually going to just copy or paste in this number here so it’s basically this long string of numbers and then n and if we were to put n right here and save we get the type of big end now as far as reference types let’s come down here and in the next video I’m going to talk about the difference in how these how primitive and reference types are stored and accessed but as far as what reference types are are arrays object literals functions so just to give you an example we’ll create a simple array I’ll call it numbers okay and then if I were to actually we want to put let’s grab this and let’s put this up here we want this above the output and then let’s change this to numbers okay if I save that it’s going to show the array as the value and object as the type okay any reference type is an object so an object literal of course is also an object is also a reference type so if I say person and we’re going to learn all about objects and arrays and get much more advanced but just to show you we’ll say Brad and then if we change this here to person you’ll see we also get object Now function is also a reference type so I’m just going to create a very simple function called say hello and just have it do a console log of hello and then down here let’s swap this out for say hello so you’ll see for the the value for the console log of the value it’s just the function itself I didn’t call it with parentheses and notice that instead of object it says function now it’s still an object it’s just defined as a function object and I’m going to put the documentation link here if you want to read more about that and in the final version of the sandbox I’ll label what these links are and stuff so I’ll make things a little neater but yeah that’s it as far as what the the types are the Primitive types and reference types or objects in the next video I just want to quickly go over how those are stored in memory all right guys so in this video we’re going to look at how primitive and reference type data is stored in memory and one thing I want to mention is if you’re a beginner and some of this is kind of confusing that’s okay that this is kind of like behind the scenes stuff and the reason I’m I’m putting it in the course at this point is just to give you a a bigger picture of not only the syntax to write for you know your JavaScript code but to also understand how JavaScript works so if you don’t completely soak in this video that’s that’s absolutely fine you can always come back to it later and we’ll talk more about this stuff later as well so when we store our data when we set a variable if it’s a primitive type it’s stored in an area in memory called the stack okay if we store reference type such as an array an object a function that’s stored in an area of memory called the Heap okay so you have the stack which is where your primitive data is stored and you have the Heap where your reference types are stored so just keep that in mind all right now to to kind of visualize how we store and access data I created this this diagram with kind of multiple scenes so first off let’s say we create a couple variables we have a name that’s equal to John which is a string which is a primitive type and then age equals 30 which is a number which is also a primitive type now this box over here represents the stack in memory so you can see age the name of the variable and 30 the value are stored on the stack same thing with name and John now if we were to create a variable called person and set that to an object which is a reference type you can see the variable is stored on the stack but it acts as accesses the data by reference and that data is stored in the Heap all right now just to kind of show you more about how this works if we create another variable called new name and we set it to name okay up here which is John then on the stack we have a new variable called new name and we have a new piece of data called John name is still equal to John and now new name is equal to John let’s say that we want to take that new name variable and reassign it remember when we use let we can reassign so now we have new name equals Jonathan so it overwrote the old value of John to Jonathan now let’s kind of do the same thing and say well we’re going to create a new person variable and set it to person which is this object right here Brad name Brad age 40 41 now but that’s fine so new person is put on the stack the variable and it points to the same reference that person does okay so it doesn’t create a whole new value like up here where we created John again it just points to that area in in the memory Heap so if we were to let’s come down here and let’s say new person dot name which is a property this property right here set that to Bradley now what’s going to happen is we’re changing in the Heap that name value of Brad to Bradley so new person.name is going to be Bradley but so is person.name in fact right here if we logged person.name it’s going to be Bradley even though we changed new person.name the reason for that is because they both point to the same reference all right so that’s kind of what I want to get across here is with primitive types the value is stored on the stack so even if you change new name to something name is going to stage on because John is there it’s solid on the stack with objects and arrays and so on you just you have a reference so if you set a variable to another variable and change something in that it changes the the reference so what I want to do now is jump into vs code and show you this this exact thing in the text editor so I have this empty script JS and we’re going to do the same thing let’s say const name equals we’ll set that to John and then we’re going to set the age equal to 30. so these are both primitive values in fact I’ll put a comment here let’s say these values are stored on the stack all right now let’s say reference values are stored on the Heap so let’s say const and we’ll say person equals and let’s set that to let’s say name and we’re going to have an entire section on object literals like this so don’t worry if you don’t fully understand the syntax so we’ll say age 40. all right so we have our permanent values and we have our reference values so I’m going to do what we did in the uh in the slide and let’s say new name and I’m using let here because I’m going to reassign it so say new name you set that to name and let’s just do a console log down here of both name and new name so now we get John and John for both the name and new name and don’t worry about this being crossed out it’s just because name is a deprecated property on the window object it has nothing to do with what we’re doing so now let’s go ahead and reassign we’ll say new name and we’ll set that now to Jonathan so if I save that now we get John and Jonathan now let’s try the same thing with the reference type so I’ll say let new person set that to person and then down here let’s console log person and new person and we get both they’re both the same right name Brad age 40. so now what I’m going to do is take new person which I got the value from uh from person but remember these are stored in the Heap and they’re accessed by reference so if I were to change the new person name to Bradley and I save that notice both person and new person both are now Bradley okay because these are both stored in the same spot in um in the Heap and they’re being accessed by reference and that diagram should really help you understand why it’s doing this right you can see they’re both pointing to the same spot but with the Primitive values the values are stored right on the stack all right so I hope that this made sense in the next video we’re going to look at type conversion because sometimes your types can change whether it’s implicitly or explicitly so we’re going to talk about that next all right guys in this video we’re going to talk about type conversion so type conversion or type casting is the process of explicitly converting a value from one type to another for instance you may have a string value of five so five with quotes around it and you want to convert it to a number of five so that you can maybe do some arithmetic operations on it or whatever you’re going to do now there’s also something called type coercion which can be explicit but it usually refers to having your types changed implicitly okay without you you know purposefully doing it so we’re going to talk about that in I think the video after the next one but in this one I’m going to show you how to explicitly convert types now let’s say we want to convert a string to a number so I’m going to say let amount and I’m using let because I’m going to reassign this but let’s set it to 100 wrapped in quotes and then let’s do a console log of the amount value as well as the type so we’ll say type of amount and if I save that you see we get 100 and string so there’s there’s a few reasons you might want to convert this to a number if let’s say someone’s submitting a form and the number comes in as a string but you want to run some operations on it you can’t do that with a string you want to change it to a number so there’s a couple ways we can do that the first is using the parse int function so we can say amount I’m just going to reassign it to let’s say parse int which is a function so we use our parentheses and this is going to take in the string okay which is in the variable of amount so now if I save that you can see we get 100 which is now a different color and we get number as the type now another way to do it is by using the the unary I think it’s called unary operator it’s just basically the plus sign and this is the method that I like to use it’s a newer way to do it so we can say amount equals and then just do plus amount so if I save that you can see that also converts it to a number and then the third way we can do it is with the number method or the number Constructor and we do that by just saying number with parentheses and then we can pass in a string and I save that you can see now we get it as a number so those are some different ways you can use to parse it to a string to a number and I’m just going to put a comment here let’s say change string to number all right now let’s look at some ways that we can change a number to a string so I’m going to come up here and change this to 100 which is a number if I save this you’ll see it’s a number and now I want to change this to a string so one way we could do it is say let’s say amount equals amount and then there’s actually a method called to string okay so a method is a function that’s attached to an object now if I save this you’ll see it’s now a string now this this actually brings up a question or it should bring up a question we know that this this right here is a number which is a primitive type which means it’s not an object now methods are properties on objects so so why does this work you know this should be a primitive it doesn’t have methods well the answer to that is Javascript actually creates a temporary wrapper if when we use two string it creates a temporary wrapper of the appropriate object type so this amount which is a primitive doesn’t intrinsically have any methods on it because it’s not an object but since we’re trying to use two string on it JavaScript creates a temporary uh wrapper of the associated type okay so hopefully that makes sense now that kind of stuff isn’t really beginner JavaScript but like I said I want to touch on some of the the fundamental concepts and how JavaScript works as you go through this course so you might not retain little things like that but that’s okay you know if as long as you remember the syntax and you know what’s going on that’s fine you don’t really have to know what happens under the hood but I will I do want to just talk about some of that stuff now another way we can do it is we can say amount equals let’s just comment that out so we’re going to say amount equals and then we can also use the string Constructor just like we have a number Constructor so I’ll pass in here Mount and now if I save that you can see that it is a string now if you have a decimal right so if let’s say this is amount is 99.5 and you want to let’s say it’s a string of 99.5 and you want to convert it to a number of 99.5 which is a decimal there’s a method you can use called parse float you don’t want to use parse int because that’s going to be an integer which is either a positive or negative number so let’s come down here and let’s say change string to decimal so what we can do is say amount equals and to use or to change it to a decimal we can say parse float and pass in the amount and then let’s save that now the actual type like within JavaScript is going to be number but let me show you what happens if we use parse int if I say Parts int and I save it’s going to be an inch it’s going to be 99. the the type underneath is still number either way but it’s going to screw up your formatting if you need this to actually be 99.5 so in that case you definitely want to use pass float all right I’m just going to change this to change change to convert okay so the next thing I want to show you is the Boolean Constructor which will turn a number into a Boolean now in JavaScript we have a concept of truthy and falsy values and I’m going to get into that soon but for now just know we can actually change a number so let’s make let’s make this back into 100 actually let’s make it into a one and then let’s come down here let’s say convert number two Boolean and I’m going to say amount and I’m going to set that to Boolean remember Boolean is a true or false value I’m going to set that to amount let’s see what we get so as you can see we get true and we get the type of Boolean now one is what we call a truthy value if we convert it to Boolean it’s going to be true if I set this amount to zero and we save we’re going to get false okay zero is a falsy value and I know that that sounds confusing but I’m going to have a whole video on truthy and falsy and then any other number like 10 or anything else is going to be true 0 is the only one that’s going to be false now let’s look at what happens if I’m just going to comment this out let’s look at what happens if we try to take a string that is not a number and or I should say is not a number in a string like something like hello and what if I try to parse that into a number let’s see what we get so we get a value of Nan or Nan and what this stands for is not a number okay it’s uh it’s actually a special number as you can see it does have the type of number but it’s a special number that represents not a number and it can this is kind of confusing um so there’s some really strange and quirky aspects of JavaScript the good news is most of it doesn’t get in your way in Practical development it’s just when we start to Dig Down Deeper if things can get a little weird so Nan is a property of the global window object and it’s a non-writable property and there’s actually five different types of operations that can return Nan and that’s when a number can’t be parched which is what we’re seeing here also math operations where the result is not a real number like trying to do like square root of negative one in fact I’ll just say console log and I know we haven’t talked about the math object yet but there’s a square root here and I’m going to do negative one if I save you’ll see that also gets Nan another one is if the operand of an argument is Nan like if I do one plus Nan let’s try that console log one plus n a n okay we get Nan also if we try to do like undefined let’s say undefined Plus undefined that gives us Nan and then the last way we can get it is any operation that involves a string and is not an addition operation so if I do like a string let’s say Foo and we’ll say divided by three I also get Nan so those are the five ways that you can end up with this but the most common thing you’re going to do here is convert a string to a number especially when you’re dealing with like form data because you might want to do some operations on a number that you can’t do on a string all right so that’s it in the next video we’re going to look at operators all right so in this video we’re going to take a look at operators so operators are symbols that we can use in Expressions to do certain things and there’s a few different categories of operators the first first one I want to look at is arithmetic so let’s say one and let’s say arithmetic operators all right so these are going to be pretty simple obviously you guys know addition and subtraction and all that but I’m just going to initialize a variable just to Output so I’ll say let X and then down here we’ll say just console log X and let’s say x equals and we’ll just do five and say five plus five so this is obviously the arithmetic the addition operator if I save that of course we get 10 copy that down let’s do minus we get zero let’s do we’ll copy that down again and we’ll do multiplication that gives us 25 and then we’ll do division that gives us one now in addition to those the you know the basic four we also have the modulus operator so if I say well if I do five and then the modulus which is the percent sign and 5 that’s going to give me zero because 5 goes into five once with no remainder so what this does is it gives us the remainder if I were to do 7 we know 5 goes into 7 once if I save that you’ll see we get 2 as the remainder so this this can come in handy for different things now the next thing I want to show you is concatenation I think you spell it concatenation so the concatenate concatenate operator is the plus sign so you can essentially think of the plus sign having two different functions in JavaScript one obviously is addition but one is to concatenate strings together so if I use the plus sign with two strings well let’s say X equals so I’ll say hello which is a string and then plus and then another string of world if I save that what it does is it just concatenates or puts the two together all right now if I wanted a space in between I could either put a space here that works or you might do another you might concatenate again just a set of quotes with a space but if I want to go back to another string then I would add another plus sign here so that’s concatenation I came to JavaScript from PHP like I learned PHP first and in PHP the period is the concatenate and concatenate operator so this does the same thing that the period does in PHP so the next one is the exponent operator which is a double asterisk so let’s say x equals and what we’re saying here is we want to get the result of the first operand to the power of the second so we’ll say two double asterisks 3 and that gives us 8. all right so that’s exponent then we have increment so increments there’s a couple ways that we can increment a number so let’s say we have X let’s set it to three actually we’ll set it to one and then let’s say I want to increment it by one I could do x equals X plus one if I do that we get 2 or I could use the increment operator which is double double plus sign if I save that I also get 2. and of course we can also do decrement so right now X is two so let’s say x equals x minus one so that’s one way that we could subtract one or we can just do x minus minus and that also gives us one so those are all the basic arithmetic operators now we’re going to look at assignment operators so the first is just a value assignment which is very simple we’ve been doing that all along so we can just say x equals 10 that’s just assigning a value now we also have addition multiplication subtraction basically all the stuff we did up here we can use those as assignment operators so what I mean is I can say x and then plus equals let’s say five and if I save that we get 15 because X was 10 but then this is the same as it’s the same as doing this x equals whatever X is Plus 5. and in fact if we did one that’s the same thing we did up here to increment right same thing as this as well and then we can also use other we can say like minus equals that gives us 10 because remember it was 15 but then we took 5 away then if we do the multiplication so we get 50 then we can do division we get 10 and we can also do modulus which gives us zero there’s even the exponent I’ve never used this but you can also do that so those are assignment operators now the next batch that I’m going to show you let’s say three these are comparison operators which you’re going to use quite a bit so the first one is is if something is equal to and I’ll comment these a little better for the final version but I don’t want to waste too much time with comments so let’s say x uh we’ll say x equals and then let’s say 2 and I’m going to use the equals operator which is double equals okay remember the single equal sign is assignment that’s what I’m doing right here I’m setting something to X but right here I’m evaluating an expression using the comparison operator of equals so what that’s going to give me is true it’s going to give me the result of this it’s going to put that into the variable and then I’m you know console logging that now if I were to change this to 4 then obviously that’s going to give me false so that’s equal to now we also have the equal value and equal type operator which is a triple equals so let’s say 2 and then let’s do triple equals two now that’s going to give me true obviously but I just want to show you if I were to comment this out for a second and then on the double equal change this to a string that’s going to give me true because the double equal does not test the type it only tests the actual value inside all right now if I were to uncomment this and make this to a string and save I’m going to get false because the triple equal not only evaluates the value but it evaluates the type as well so the types have to match and in this case this is a string this is a number now it’s really preference on what you use but what I do and what I’ve what I see a lot of people do is pretty much always use the triple equals I think that that’s going to save you some headaches and save you some hours if you just always use triple equals there are a couple situations where you might not want to there’s there’s quite a few where you don’t need to but it’s in the most in most cases it’s not going to hurt all right so that’s just what I do it’s up to you you’ll you’ll kind of find your groove as you as you move along all right so let me just put a space here now we also have not equals so I’m going to say x equals 2 and the knot is is represented with an exclamation so I’m going to say not equal but just one equal in this case so this is this is basically the opposite of this even though it only has one equal sign so I’m going to say 2 and save that and we get false and the reason we get false is because 2 is equal to 2. so obviously 2 not equal to 2 that expression is going to be false now same rule applies with the double equals as with this if we were to do a string that’s still going to be false because in this case 2 is equal to this if we’re using the double equals now we also have the not version of this so if I were to copy that down and then let’s just add another equals onto that if I save that we’re going to get true and that’s because it’s true that this is not equal to this when we’re checking the type as well if I remove these quotes and save that that’s going to be false because it’s false that this is not equal to 2 because they are equal all right now the next thing I want to show you is greater than less than which are pretty simple so let’s say x equals 10 let’s say greater than 5 and then of course that gives us true and we’ll just copy this down and let’s change this one to less than so that’s going to be false we also have greater than or equal to and we have less than let’s do yeah I’m sorry that’s less than or equal to then we also have greater than or equal to so very simple those don’t really need any explanation if you did like third grade math so that’s all I want to talk about in this video basically I needed to you guys to know this stuff in order to understand the next video of type coercion so a couple videos ago we looked at type conversion where you as a developer you want to change a string to a number or a number to a string in this video we’re going to look at type coercion which is more implicit and typically coercion happens when you apply operators to values that have different types so what I’m going to do is just create a variable of X and I want to console log the value of x and also the type and the reason I do this is just so we don’t have to create a bunch of different variables so let’s say we want X to equal the number five plus the string with 5 in it and let’s see what we get so if we look in the console you’ll see we get 55 but we get it as a string so this is an example of type coercion where JavaScript implicitly changed this to a string all right because what happened here is it was concatenated with the plus sign so if I were getting a string for some reason and I wanted to add it then I would convert this first so for example actually let’s just copy it down because I’d like you guys to have all the code we write and let’s just wrap this in a number and then that will obviously add them together because now this is a number now what if we were to say x equals five and then let’s multiply a string what do you think we’re going to get here so if I save that we get 25 which is a number so JavaScript in this case did the opposite it converted or coerced this string into a number and the reason for that is because if you use multiplication between strings that doesn’t make any sense you’re not going to get anything from that so JavaScript decided to coerce it to a number so it could be multiplied so let’s see what happens if we do x equals and let’s say 5 plus null in that case we just get 5 as a number so no is actually coerced into a zero and we can see that if we do let’s say x equals and we’ll use the number method here and pass null in and you’ll see we get 0. okay and you can use this on anything this number so if I say number let’s do copy that down we’ll do true and false I’m just going to comment out this one to see what we get for true you can see we get one so true as a number is one false as a number is zero so with that said what do you think happens if we say let’s add five plus true let’s go ahead and save that we get 6 because true is being coerced into a number and true as a number is one okay same if we do let’s say five plus false obviously we’re going to get 5 because false is zero as a number and again we’re going to talk about truthy and falsy values in a little bit so if we do let’s say x equals 5 plus undefined we get Nan which is not as a number now remember in the what was it was it the last I think it was the last video where we talked about Nan and if we add anything to undefined um then we’re going to get Nan okay including itself so now you should be pretty familiar with types we have our seven primitive types and then we also have reference types or objects and we talked about how they’re stored in memory we talked about implicit and explicit type conversion or coercion so what I want to do now is focus on individual types such as strings and numbers and start to look at how we can use them manipulate them use some of the methods that we can use with strings and numbers and just get you a little more familiar with that all right so we’ll look at strings next all right guys so we’ve looked at the different data types the Primitive types versus the reference types or objects we’ve looked at conversion and coercion and operators what I want to look at now is individual data types and just certain things we can do so in this video I want to look at strings so we’ll talk about concatenation a little bit more as well as template literals which are really really helpful and also some of the different methods that we can use on a string now like I said in a past video strings are primitive however they if we use a method like let’s say two uppercase on a string which is primitive JavaScript puts a wrapper around it and makes it a string object so in that case we can use methods all right so let’s start off here by initializing a variable I’m just going to say let X because I’m going to do a lot of output so let’s say console log X and then we’ll start off here with concatenation which we’ve already gone over we basically have our string actually you know what I’ll do is uh let’s let’s do like a sentence we’ll say hello my name is and then I want to put a variable and I’ll set those variables here let’s say name equals John or whatever you’d like and then let’s say const age equals 30. now here I want to use the name variable so what I would do is concatenate name and you don’t want to put quotes around this because it’s a variable and then we want to concatenate back into a string and never mind this strikethrough it’s just because the window object has a deprecated property of name but it doesn’t concern us and then I want to say and so my name is John and I am space concatenate on the age plus and then let’s do another space here in the quotes and years old so that is you know kind of kind of a pain in the ass but if I say we say hello my name is John and I’m 30 years old if we change this to let’s say 31 and save obviously that’s going to Output now I want to show you how to do this same thing using something called template literals also called template strings so I’m going to take X and just overwrite what we just did and I’m going to use back text this time okay so back ticks are used for template literals not quotes and then we can do the same thing we’ll say hello my name is now instead of having to you know put a space here and then concatenate here what we’ll do is use this syntax a money sign and then curly braces and then in here I can put my variable if I save that you’ll see it says hello my name is John now this isn’t just for variables the syntax it’s for any JavaScript expression in fact I could just do like one plus one and it’ll evaluate it to two so we can essentially write our JavaScript in here so I just wanted to say name and then I’m going to just space and then and I am I want to put my age here so again I’m going to use the syntax and say 30 31 years old and you can see that that output’s fine so this to me at least is much much easier and cleaner than this so you’ll be using template literals quite a bit now template literals didn’t come into JavaScript until 2015. it was the es2015 or es6 update was where template literals were were introduced before that you would have to do this so now what I want to do is look at properties and methods or let’s say string string properties and methods so if I say let’s say x equals and then hello world actually I’m going to give this a different variable let’s say const s equals hello world so we have a string of hello world and if I want to let’s say get the length there’s a length property for that we can use for Strings so I’m going to say x equals and then s which is our string and then dot length now since it’s a property we don’t add the parentheses methods use the parentheses because methods are functions properties are more like attributes so if I save that you’ll see we get 11. now as I S as I said earlier the strings are primitive but we can use properties and methods on them because of the wrapper that JavaScript gives it when we run these properties and methods so essentially what JavaScript does behind the scenes Let me just show you real quick if we were to do let’s say x equals type of and then we’ll do type of s and let’s just comment that out because that’ll overwrite it so we get string right but what the wrapper does when we run a property or method is it basically says new string and it creates this string object now if I save you’ll see I get object okay and I’ll just leave it like that you can leave it with just quotes hello world or you can use this new string but I’m just trying to let you know what happens kind of behind the scenes when we use a method or a property and we can also access the the the individual characters so for instance if I say let’s go down here if I say x equals and then S I can use this syntax and it starts at zero just like an array if I save that you’ll see I get H I get the first character if I do one I get e so I get the second character and so on okay and I’ll just put a comment here we’ll say access access value by key so we have number key numbered keys now another thing I want to show you and we’ll get much more into this later with object oriented programming is objects have what’s called a prototype and that’s where the methods are stored so if I do x equals and the way we access the Prototype is double underscore Proto double underscore and I’m setting that to X so I’m going to save and show you what we get here so if we look down here we have all these different methods so for instance we have two uppercase two lowercase we have split substring all these different methods that we can use with strings and I’m going to show you some of them not all of them I’ll show you some of them now some of them later and and some you’ll never use which I probably won’t won’t get to but you can see all these different methods that are available on the Prototype so and if we console log s and I save that if we look down here you’ll see prototype right here which has the same thing so this is is the same thing as this all right and it even shows you the different Keys the different numbered keys but let’s put that back to X and now we’re going to look at some of these these properties so if we want to change the case we could do x equals let’s say our string and then we’ll do two uppercase which is a method so of course we need our parentheses if I save that we get hello world and all uppercase I’m actually going to comment that down and we also have two lowercase okay so that will change the case there isn’t a method that will make like the first letter of each word uppercase but we can do that in JavaScript it just there’s no single method to do it I’ll show you that in a little bit so the next one is Char at and that will return the character at the specified index so if I say x equals s dot Char at and let’s say we want to get the first character that would be zero if I save that that gives us H which is essentially the same as as what we did up here where we were accessing by the key so this will give us the same as this now if we want to know the index of a specific character so kind of the the inverse of this we could say s equal x equals s and we can use index of so if we say index of and let’s say we want the index of H if I save that we get zero let’s say e now there’s more than one e what this will do is give us the first e which is the the number one index which is the second character so this right here because it’s 0 1 2 3 and so on if we put let’s say d that will give us 10 which is the the last index so the next one is substring which will search a string for a specified value so let me show you if we do s dot and then substring and then we can this will take in two indexes so let’s say we want to get from 0 to 4. if I save that we get hell because if we look at hello world and by the way this could be just a string you know just the quotes hello world if I change this s to that and save we get the same thing but I just did that to show you basically how to how to turn a string into a string object so we get hell because it’s 0 1 2 3 and then it ends at four all right if we want to get hello then it would be zero to five save that we get hello and we don’t have to start from zero if I do one and save we get lo you know Edo Governor if we do 2 to 5 we get llo all right so you can get any it’s it’s a substring it’s just basically a string inside of a string and another thing we could do is run substring with a single argument let’s say seven if I save that we get o r l d so what this did is it started at seven and then it just gets the rest of the string all right so zero one two three four five six seven so it started here o is seven and then just went to the end if I put a bunch of stuff on the end of this and save it’s gonna add that to it now the next one I want to show you is slice which is very similar to substring in fact I’m going to just copy this and we know that 0 to 4 will give us access to zero to five that’ll be hello and actually I’ll just save it you’ll see it get hello with substring and if we do slice we also get hello now there’s a few differences one of them is that with slice we can start from the end with negative numbers so for instance if I do let’s start we know that hello world altogether is 10 right it’s 10 characters or 0 through 10 I should say and if we want to start the beginning using negative we could do negative 11. so if I do that and then actually if I just do that we’ll get hello world because it starts at the beginning negative 11 all the way to the N now if I want to get the word hello we could do let’s see that would be negative 10 nine eight seven I think negative 6 should give us so if we save that yeah so that now we get hello so we’re basically just starting from the end yeah so I mean you could use substring or slice interchangeably in a lot of different situations another one that I want to show you is trim so let’s uh let’s say s dot trim and what this does is it trims the white space so what I’m going to do is set let’s just do this we’ll say hello world but I’m going to add you know a bunch of white space here and if I were to just do that you’ll see it it adds the white space here to the beginning but if I were to use trim and say x equals x dot trim and save it gets rid of that white space so that can be pretty helpful next let’s look at replace so I’m going to say x equals and let’s set um so we’ll take string and then we want to replace and let’s say we want to set the word world to I don’t know John so what we could do is search for a string within a string that’s going to be the first argument so we’re going to search for world and then the second is what we want to replace it with so let’s say John if I save that we console log X now we get hello John now let’s look at includes which will return true or false if a string is found within that string so if I say s dot includes and we want to let’s say we want to find hello if I save that we’re going to get true because this is found within that s string if I do hell that’s going to be true if I do Hal e or how I I save that that’s going to be false because this string is not found it’s not included in the hello world string okay so that’ll return true or false and then if we want to return the Primitive value of a variable so let’s say x equals s dot we can use value of and if I save that we’re just going to get the hello world okay even if we were to do this up here so this is a string object right if we console log s we get the string which is an object if we did type of acid should show object but if we want to get the true primitive of that which is a string we would use value of and then the last one I want to show you is split which you I use I’ve used quite a bit it’ll split a string into an array and it takes in a separator as an argument so let’s say s dot split and then if I just do that on its own it’ll just give me an array with the entire string inside of it now let’s say we want to split by the space because it’s hello space world then we would pass in here a space and now you’ll see I have an array with two strings and I know we haven’t really gone over a raise yet but we get an array with two strings okay if I wanted to split every character into an array item then I would just put just quotes if I do that now we have an array with 11 of items and each one is each character okay so that’s split now there’s a lot more methods so you can see here and I’m going to go over some of these in future videos some of them I won’t because they’re not really used that much but of course you can experiment on your own as well so I hope that this helped you understand some of the things we can do with strings now in the next video I’m actually going to give you guys a challenge based on the stuff we’ve already learned all right guys so we’ve arrived at our first challenge every once in a while I’m gonna ask you to figure out a problem or do something using the stuff that we’ve already learned okay I’m not going to ask you in any challenge to do something that involves something we haven’t done yet or haven’t learned yet now if you feel stuck or you can’t figure it out on your own that’s absolutely fine I’m gonna walk you through the solutions so that you can really understand how to solve the problem now this one is the capitalize challenge so basically what I want you to be able to do is take a string with a single word and just make the first letter uppercased we know we can do like so I could do my string dot two lowercase which would make it all lowercase or my string dot two upper two uppercase would make it all uppercase I want you to just uppercase the first letter now it doesn’t have to be a string with multiple words where you uppercase the first letter because in order to do that you have to to understand some type of iteration and I haven’t gone over any Loops or anything like that so I’m not going to ask you to do that if you already know that stuff and you want to do that that’s absolutely fine but yeah I just want you to basically take this my string which has a string of developer or it could be any word and when you console log my new string which should be a variable you create that has the uppercase D for developer or whatever the word is now just to give you some hints because this is all stuff we went over you can use the Char at method which will give you a character at a specific index you could also do this format where you have you know my string and then brackets and 0 1 2 3 Etc so you know how to access the first letter and then you also know how to make all of these everything uppercase and then you also know how to basically pluck out stuff from the string okay take strings from a string using either the substring or slice methods okay so using this stuff here you should be able to uh you know come up with this my new string which will have an uppercase for the first letter all right so go ahead and pause the video now and try and do that on your own so now what I’m going to do is close that up and we’re going to go ahead and solve this Challenge and I’m just I just want to open up my console over here as well so we know that we have a variable called my string and that’s set to a word a single word that’s all lower case we’re going to use developer and then I’m going to have multiple Solutions but they’re all going to be very very similar so I’m going to initialize my new string and let’s say this is going to be Solution One so we want to take my new string and then I want to set that to my solution now let’s remember the hints Char at is used to get the character at a certain index you can also use the bracket syntax and we know we want to get the first first thing here right first character so let’s say my string and then let’s use Char at and let’s say zero okay and then let’s just do a console log down here of my new string and the goal of this is to get my new string to be the word developer with with an uppercase D so we know that we can get the first character like this now let’s take that first character and make that uppercase so we can do that by chaining on to uppercase right so if I do that and I save now we have an uppercase d so what we need to do now is basically just take the rest of the string not including D and concatenate it onto it so let’s go ahead and I’m just going to close that up let’s concatenate and then I’m going to take my string which is developer with a lowercase D and I’m going to use substring okay so I’m going to say substring and I want to get just developer okay no D so what I can do is just put a 1 in here because what that’ll do is take the one position which which is e remember it starts with zero and it’ll get that over all right so now if I save this I’m going to get developer with an uppercase d now the other Solutions we can use are going to be very similar so let me just copy that down we’ll say solution two and then the only change I’m going to make here is instead of using Char at we can just use the bracket syntax so we can say my string and then we want to get 0. we’re going to uppercase that so that that makes the D uppercase and then again we’re just going to tack on or concatenate the substring which is the the rest of it the available if I save that we get the same thing so let’s grab these and copy these down and then this is going to be solution three and in this case what I want to do is instead of concatenating I want to use template literals so I’m going to get rid of the plus and basically what we have here are two different Expressions right the first one gives us uppercase D the next one gives us developer so I’m going to take the first expression and let’s put our back tick here and we’re going to wrap this first expression in curly braces okay and then the second one here we’re going to wrap that as well so that ends here and then we want to make sure we put the ending back tick on and we don’t need to put a space here so if I save that we get developer if I were to put a space here we’ll get this uppercase D and then available and another thing we could do is instead of using substring we could use slice okay so it just shows you that there’s multiple solutions for everything really and there’s a lot more solutions you could have including stuff that we haven’t gone into yet but as I said when I have a challenge for you guys it’s going to only include stuff that we’ve already gone over now if you wanted to uppercase every the first letter of every word you would have to iterate through it somehow and we haven’t gone over like for Loops or four each or any of that um so you know we have gone over turning a string into an array so you can take that as a clue as a hint if you do want to try it on your own but but that’s it for this challenge let’s go into the next video okay so just like we have string or methods and properties that we can use for Strings and we have string objects we have the same for numbers so let’s go ahead and create a variable here and I’ll set it to let’s say the number five and then I’m going to console log down here if I log number we get five if we look at the type of this variable it’s a number now we can also have number objects using the number Constructor so we can say new number and it probably won’t be too many times where you use this explicitly but like I said before it does JavaScript does put a wrapper around it and turn it to an object if you use methods but if we look at the type you’ll see now we get object and you can set this to five if you want or keep it like this I’m just going to keep it like this and then I’m going to just create a variable for our output because I just want to show you some of the methods that we can use now we’ve looked at two string so if we say num dot to string that’s going to give us the number as a string now there is no length property for numbers so if I were to say x equals num dot length you see I’m going to get undefined however if you want to get the length of a number like you want to know how many digits it is you could do two string right so just turn it to a string and then chain on length and now you’ll see I get one if I were to add let’s say let’s say 500 then it gives me 3. all right so that’s two string we also have two fixed which is going to give you or allow you to specify the number of decimal points so let’s say dot two fixed you can see we have the drop down of methods here so two fixed and I’ll say two and even though our number is 5 it’s just going to give us 5.00 now if we look at the type so if we look at the type of X you can see it is a string so if we take a number and then we use two fixed on it it’s going to turn it into a string representation of a decimal so let’s get rid of that and then if I were to let’s say this number I’ll make it 5.4567 if I save that I’m just going to get 5.46 now it gives me 6 because it rounded this up right if I were to do 4.52 and save that then I get 4.5 now we also have two Precision which is kind of similar but we count we we count the whole number so if we say three actually let’s do two and I save it then it doesn’t give me two decimal places it gives me two in total so we’ll do 5.5 and if I were to change this let’s say 4 5 to 4 2 and save that it’s going to give me 5.4 right if I say two Precision three then it’s going to give me three digits 5.42 so that’s two Precision we also have two exponential so say x equals nine dot nine num dot two exponential and that will get us the exponential of let’s say say two if I save that then we’re going to get that as a result let’s actually change this back to five so two precision and two exponential are ones that I don’t really use very much now you you might be working in a different location a different Locale so there is also two Locale string so if we do that and then I mean by default I think it’s going to do where you are so for me it would be en us since I’m in the US which just gives me five but let’s say you’re in Egypt which is I think AR Dash e g and save that’s the representation of the number five I guess I mean I don’t I don’t know the Egyptian numbers or whatever but I’m guessing that’s what it is all right so that’s two Locale string I’m just going to put that back to en dash us now there’s not too much else to look at as far as methods if we do num and we look at the Prototype I mean that’s pretty much it all the ones we looked at right I mean there is value of as well so if I do x equals num dot value of and we save that let’s console log X that just gives me the value right now there are on the number object itself there are properties so for instance we can get the largest possible number for the number type by doing number with a capital N Dot and then all capital Max underscore value so I’m going to set that to X so that’s the largest number possible that we can use with number and then if you want to get the lowest possible we can do x equals let’s say number Dot and then min value which is that number there okay so there’s not much else to look at in terms of methods that we can use on numbers so in the next video I want to look at the math object all right guys so JavaScript has a built-in object called math and this object has a bunch of methods on it that have to do with mathematical operations and it comes in handy when you need to do things like find the square root of something or round up or round down there’s also a helpful random method that you’ll probably use quite a bit so we’ll go ahead and take a look at that I’m just going to console log the math object itself and you’ll see that we have an object here that has some properties so it has pi for example and then a bunch of methods and I’m definitely not going to go over all of these and so some of them I don’t even know what they are or what they do and I’ve never used them but we’ll go over some of the common ones so let’s do let’s just create a variable to work with for our output so we’ll console log X and let’s say x equals let’s say we want to get the the um the square root of a number so we’ll do math Dot and then sqrt okay so that will get the square root of a number we’ll just pass in 9 here and if I save that we log out X you can see we get 3. so that’s the square root if we want to get the absolute number then we could use the ABS function so our method so we’ll say absolute and if I do 5 obviously that’s five if I do negative 5 we also get 5. that’s the absolute so we can also round let’s say x equals math dot round and let’s put in here let’s say 4.6 if I save that we get 5. if I put 4.2 and save it we get 4. now you can also round up or round down so for instance let’s do a round up and that’s going to be with the seal method so it’s going to be c e i l like ceiling and let’s put in 4.6 or I’m sorry let’s put in 4.2 and if I save it still goes to 5. okay so this will just round it like normally and then this will always round up so even though it’s 4.2 it’s rounding up to five now you can do the opposite and round down with the floor method so if I were to do math dot floor obviously that’s going to give me 4 but if I even if I do like 4.9 and I save that’s still going to give me 4. so these are pretty common seal and floor I use those in a lot of different situations um another one is pow so it will return the value of our number raised to a specific power so let’s say math Dot pow and let’s say we want to do 2 raised to three then we get eight okay we can also do the Min and Max so let’s say x equals math dot Min and what this will do is return the smallest of two or more numbers so if I do let’s say four and five and I save that’s going to give me four if I do another one pass in 3 that’s going to give me three and we can do the same thing with Max so if I were to do math dot Max and pass the same in we’re going to get 5 because that’s the largest of the three now a really common method is the random method so let’s say x equals math Dot random all right now if I run this what it gives me whoops it should be uppercase if you just use lowercase it’s going to look for uh just a variable called math so you have to use uppercase so what this will do is you’ll see I’ll keep reloading the page and every load it’s going to give me just a random decimal between 0 and 1. now that’s usually that’s not usually what you want usually you want to get like a number from say one to ten or one to a hundred so what you would do and what you’ll see a lot of let’s just um let’s use a variable of of Y here so I’ll say let y and we’re going to set that to math Dot random and then if we multiply that by 10 let’s see what we get we want a console log actually let’s just use x I don’t know why I did that okay let’s just do that now what that’s going to give us is a decimal between 1 and 10 right so if I keep reloading here actually I’m sorry not one and ten zero to nine now if I want it to be a decimal between 1 and 10 then what I would do is add 1 to this so let’s just put a plus sign here and then we’ll add one now it’s going to be one to ten let’s see if I can get 10. there it is so it’s going to be 1 to 10 as a decimal now what you want to do to make this a whole number is just round it down so we’re going to say math dot floor and we’re going to surround this whole thing and there we go so now we’re going to get a number between 1 and 10. if you want it to be between 1 and 100 we could just do that okay so you’ll see this this exact thing you’re going to see quite a bit because there are many times in programming in general where you need a random number and like I said there’s other methods on the math object if you want to check those out you can we might be looking at some of them later on but in the next video what I want to do is give you a little challenge that involves numbers as well as generating random numbers with with math.random all right so we’re going to do a little challenge here now keep in mind any challenge that I do it only involves stuff we’ve already worked with so I’m very limited with the types of challenges that I can create like I can’t have you guys create a function or anything because I haven’t gone over functions yet so some of these might be a little strange but it’s it’s all I could come up with with what we’ve gone over so far so basically what I want you guys to do is create a variable called X that is a random number between 1 and 100 along with a variable called y that is a random number between 1 and 50. and then I want you to create a variable for the sum the difference the product the quotient and the remainder of X and Y all right and then log the output in a string that shows the two numbers of X and Y along with the operator and result so basically you should have some variables like this that when you log it actually shows something like this 31 plus 15 equals 46 and along with the difference product quotient and remainder for a remainder you can use the modulus operator and then as far as hints the math.random function returns a floating Point pseudo random number in the range of zero to less than one so basically a random decimal and then the math.floor function will round a number down to the nearest integer so we talked about all that in the last lesson so go ahead and pause the video and see if you can just do this go ahead and create like I said X and Y random numbers between these ranges and then have these variables output these strings with the actual equation okay so let’s go ahead and get started so first thing I’m going to do is create my variables let’s say const and we’ll do x equals and remember X should be 1 through 100 a random number and Y should be one through I think it’s 150 I said I say 50 or 150. I think it was 150. so let’s say math dot floor because remember we want to round this down if we don’t use math.floor it’s going to be a decimal in fact let’s just let’s let’s do without it first just to see so we’ll say math.random and I’ll just log stuff as we go so we’ll say console log X and we get just a random decimal that’s going to be less than one basically and then if we want this to be between 1 and 100 what we could do is multiply it by 100 and that’s going to give us what 0 it’s that’s going to include zero so we want to do plus one if we do that then it’s going to be one between one and a hundred but it’s a decimal so that’s why we need to math.floor and round it down all right so now we have a number between one and 100 and then y I’m just going to copy this down Y is going to be between 1 and 150 so we’ll change this 100 to let me just check that did I say 50 or 150 oh I said 50 all right so we’ll change that to 50 and if we log X and Y then we’re going to get random numbers first one’s going to be 1 100 second is to 50. now we want to create variables that will show whatever X is plus whatever Y is equals whatever it equals we want to do the same for the difference in product and so on so what I’ll do is create a variable called sum and we want to get the value first so let’s say X Plus y and we can log out here some so we get 19 right so it’s just generating random numbers and adding them now let’s create another variable I’ll call this some output and by the way if you did something completely different as long as you get the same kind of output that’s absolutely fine there’s so many ways to do this so I’m going to set that to a template literal and in here I’m just going to take X and then say Plus and I’m wrapping these because they’re variables so I’m wrapping them in this money sign curly braces and then let’s say equals and then whatever the sum is okay and then let’s do just a console log because I want to log them all out we’ll say const output or console.log sum output and we can get rid of this and now you’ll see we get 34 plus 12 equals 46 which I think is true if I reload 19 plus 28 37 plus 3. all right so we we get the addition working now we’re going to do kind of the same thing for the difference let’s say this will get some or get the sum and what we can do is just copy this whole thing here and let’s say get the difference and let’s do we’ll call this um diff and we’ll do subtraction let’s say this is going to be our diff output and then this will be minus this will be diff and then diff output okay so if I save that then we get 78 minus 43 equals 35. all right now let’s go ahead and do the product so let’s call this um prod so like I said you just have to have the same time the same output not the same numbers obviously because it’s random but the same kind of output it doesn’t matter how you format this it’s still correct so prod output let’s do that and then that’s going to be the product and then this will be prod output there we go and then we want what else the quotient so we want to do division say quote q-u-o-t output and that’s going to be division so slash and quote and quote okay so we get 68 divided oh that’s not right oh I have a plus sign here make sure that we change that so 1 divided by 12. so we might get decimals here but that’s fine all right now the last one I want to do is the remainder so let’s say get the remainder and I’m going to use RM for the variable and then let’s change the plus to a modulus operator which is the percent sign we’ll say RM output and let’s make sure we change that to the percent sign this is going to be RM and then we want to log out the RM output and there we go so 543 modulo 5 is 3. good now like I said I know that this this is kind of a weird challenge so congrats if you got it but if you didn’t really understand it I I understand that because I only had so much to work with you know I couldn’t have you guys do something that I didn’t explain yet so that’s it in the next two videos the last two videos of this section we’re going to look at dates and times because those are something that are really important and in most areas of programming especially in web development where you have different resources like users and blog posts and all that and you want to have dates so you sign up dates and post dates so something that’s pretty important so we’re going to look at that in the next video all right guys so date dates and times are important in programming and JavaScript has a date object that represents a point in time and lets you do some basic operations on it so basically we can instantiate a new date object with the new keyword so I’m just going to create a variable here just so I don’t have to keep creating new ones we’ll just use this D variable and let’s set D to a new date now if I do this and I console log D you’ll see down here we get Friday October October 28 2022 it has the time it gives me the the time zone now this if we look at the type of this so if we say type of D we get object so the data is an object basically anything that’s not a primitive type is going to be an object now you can turn this to a string so I’ll say d dot to string if I do that then that’s going to be a string all right now if we want to set a specific date what we could do is say new date and then in here we can pass in a value so let’s say we want to do 20 20 we’ll do 20 21 and let’s say 6 10. and if I save that you’re going to see it’s Saturday July 10th now this might be confusing because we use 6 here but yet we’re getting July which is the seventh month so the caveat is that the month is zero based or zero index so if I put a 1 here then we’re going to get February if I put a 0 here then we’re going to get January okay so keep that in mind now if you want to add a time we could keep adding on to this let’s say we want 12 so that’ll be the hour and then we have and you can see right here we have the hour and then we can do minutes seconds so let’s say 12 for the hour we’ll do 30 for the minutes and 0 for the seconds if I save that you can see now we get 12 30. now instead of passing in arguments like that you can also pass in a string so are many different types of strings I should say formatted in many different ways so if I do a string so quotes here 20 21 let’s say Dash zero seven and let’s say 10. if I save that then we’re going to get July okay so set this is going to be correct so 7 is July if we do it like this and we pass in the separate arguments then the month is going to be zero based and if I wanted to add the time there’s a few ways I could do it I could do T and then let’s say 12 colon 30 colon zero zero if I do that now you’ll see the times 12 30. I could also do it this way so let’s clear this up and I could do let’s say 07 slash 10 slash 2021 and then I could do a space 12 30. like that and we get the same thing now there is a known issue if you use if you use hyphens and you use the year first then it could be off by a day due to the time zone so if I do let’s say do a string of 20 22 and let’s use hyphen so I’ll say 0 7 and 10. and then save that you’ll see it actually says July 9th even though I said July 10th so keep that in mind if you do the year first and hyphen it might be off by a day if your time zone is not set um if you put the month first it should work so if I were to do like seven 10 22 which is you know in the US is how we format dates then that does say July 10th and I’m going to put a link here to a stack Overflow that kind of explains why this uh why this happens so the next thing I want to look at are timestamps so the Unix timestamp is a system for describing a point in time and what it is it’s an integer that represents the number of seconds that’s elapsed that’s passed since the date of January 1st 1970 which is an arbitrary date so that that time stamp is expressed in milliseconds so or I should say the timestamp in JavaScript is expressed in milliseconds now you can always get the time stamp by using let’s say d so by using date dot now like that so if I save that we’re going to get the milliseconds that have passed if I reload you’ll see it’ll just keep updating right so that that gives you a way to always be able to mark an exact you know millisecond in time and we use timestamps for different things and we’ll probably use them throughout the course now to get a time stamp of a specific date you can use the get time function or method or you could use value of so for instance let’s say d equals and we’ll create a new date let’s just say we’ll do we’ll do the same thing seven we’ll do 10 in 2022. okay and then I’m going to get the time stamp by saying d dot get time actually I want to I want to log that so let’s how should I do this let’s set that to D so we can see that logged all right so this is the exact time stamp for this date now I didn’t put a time in here so we might want to do that so we could do like let’s say 12 30 0 0. okay so that’s always going to be that exact time stamp and then again you can also use value of so if I say d equals D dot value of and save I get the same thing if I want to get the exact time stamp for right now this date and time I could just clear that up and save and obviously that’s going to keep changing okay as time moves so you can also create date objects from a time stamp so let me just grab this right here which was a couple seconds ago and then I’m just going to say d equals new date and just like we can put in arguments or we can put in strings we can also put in a time stamp and then let’s save that you’ll see it’s October 28th and it’s going to be nine o’clock 49 seconds that’s what this time stamp represents right now it’s 901 okay so that was about a minute ago so let’s see the JavaScript timestamp is expressed in milliseconds if you want to convert it to seconds then what you could do is and just ignore the D equals for all these the only reason I’m setting it to the D is just so we can log it and see what what these actually give us but we could just do math dot floor and then we’ll take the date dot now which will give us the the time stamp of right now and then simply divide it by a thousand because there’s a thousand milliseconds in a second we save that and that’s the timestamp in seconds okay just remember in JavaScript by default the timestamps are milliseconds so in the next video I just want to look at some of the different methods that we can use on date objects and we already looked at the get time and value of but there’s a bunch of others as well that we’re going to look at all right so in this video we’re going to look at some of the methods on the date object now I just want to mention I I know that this isn’t the funnest stuff in the world but it’s really important to understand the basics and the fundamentals before moving on to you know building projects manipulating the Dom and fetching data and all that okay we’ll get to that but I think it’s important to know the basics so what I’m going to do here is just create a variable for our output and then I’m going to initialize a date variable so we’ll say new date and I’m just going to use today’s date so I’ll leave that I’ll leave that empty the argument’s empty and then let’s just do a console log of x now I know this might be a little confusing this new keyword we’ll get to that later we’re going to get to object oriented programming and get deeper into JavaScript but for now just know that what we’re doing here is we’re instantiating or initializing a date object into this D variable okay now with like the math object that we used a few videos back we would just do math dot whatever square root and we use the math object directly in this case where instantiating a date object into this variable okay so I guess that that’s a good enough explanation for now we’ll get more into it later so we already looked at some of the some of the the methods such as tostring okay so if we do two string it will just give us a string representation of the date we also looked at get time and also D dot let’s say value of okay so those will both give us a time stamp of the date in milliseconds now if you want to get specific parts of the date we can do that so let’s say we want to get the the year so we’ll do D dot and then there’s a get full year method and you can see it gives us 2022. now if I were to change the date up here by putting in let’s say 20 we’ll say 2020 slash 10 12. if I do that then the year is going to obviously change to 2020. all right now we can also get the the month so let’s say d dot get month now look what happened here uh oh I used a colon so notice that it says nine and right now it’s October so this is actually one month behind so when you use get month just like the caveat when we use the the arguments the month is going to be zero based okay so if I were to make this date January looks let’s say one two twenty twenty now you’ll see I get zero for the month so just just know that that’s zero based what you could do is just add a 1 to this and then that will give us the correct month all right and then if we want to get the day of the month so we’ll say d dot and that’s going to be get date if I do that I get 28 today’s October 28th if we want to get the day of the week then we do get day okay so get day or I keep putting a colon so get day will give us the day of the week get date will give us the day of the month now we also have some methods that have to do with time like if we want to get the the current hours we can do get hours if we do that you’ll see I get 9 it’s 9 37 right now if we want to get the minutes we could do get minutes so 37 if we want to do seconds we can get seconds so pretty self-explanatory and then we can also get milliseconds so we’ll say d dot get milliseconds all right now there might be times where you construct a date from these methods so for instance if I wanted to do let’s say create a template literal with back ticks and then I could use this syntax to put in my whatever whatever I want to put in here variable any JavaScript expression but let’s say we want to get the full year and then I’m going to go outside of that the curly braces and put a hyphen and then we’ll do D dot get let’s say get month but let’s add a 1 to it and then we’ll do another hyphen and then we want to get the day of the month so we’ll do D dot get date and if I save that um what did I oh I forgot the parentheses on the full year and there we go so now we have a string representation of the date using these methods so I I found myself doing stuff like this in real projects now there’s an API that we can use for dates it’s it’s called intl dot date time format and it’s a more modern and Powerful way to format dates in a Locale sensitive way because obviously you know different places they they interpret dates and times in different ways so we can actually pass in arguments like en-us for the United States or whatever the Locale is so let’s let me give you some examples of that so we’ll say x equals and it’s going to be I so capital i n t l dot and then date time format okay and then I’m gonna put in my Locale which is en-us and then let’s do Dot format and then I’m going to pass in my date my D variable so if I save that I get this 10 slash 28 22. now if you’re in the UK this might look a little weird to you so what we could do is instead of en US I could say Dash GB and then it’s going to put the day first which looks crazy to me but you know every country every area is different to get your default Locale you could just pass in default all right so if I do that it’s going to go back to the US because that’s where I’m located now if you wanted to just get like let’s say the month I’m just going to copy this down you could add options in here so after the default I’m just going to put a comma and then open up some curly braces and we could say month say we want to get the month and then let’s say we want the long format so we’ll just say long as a string if I save that it’ll just it’ll give me October all right and I’ll show you some of the other options in a minute but there’s a shorter way to do this right now what I’m doing is calling the API and then I’m passing in the date which is our D variable but on that D variable you have a method called two Locale date string and if we do that or actually you can just use two Locale string and then we can pass in the Locale I’ll just say default and then I could pass in options like for instance if I want to do let’s say month and get the short and I’ll paste the link in here to the documentation where you can see how you know more about this API but you’ll see I get ocked okay so instead of having to do this intl day format and then pass in your date you’re just calling a method on your date object and getting the same thing now I’m just going to put paste in here let’s see I’m just going to paste in this and let me just set X to that so we can log it and if I save that we get Friday October 28 2022 at 6 49 11 am which is not correct that’s not my time zone I don’t know why I have Los Angeles here I want to do I think it’s new underscore York there we go so that’s more like it but yeah so you can do weekday now if you just wanted for instance the weekday you could just pass that in like that and you get Friday so this is a newer way of doing things rather than this up here using the this this date time format API and that’s what I would probably suggest using uh you know it’s more location specific and you can format your dates and get whatever you want from the date pretty easily alright guys welcome to section two in this section we’re going to learn all about two really important data structures in JavaScript and that is arrays and objects or object literals I’m going to show you how to create them manipulate them using specific methods Nest them and some other stuff now since this is the beginning of the course I’m not going to get into really Advanced operations yet I’m not even going to get into like high order array methods for those of you that know what that is or any kind of iteration or Loops we’ll do that a few sections from now I just want you to really understand how to create and work with arrays and objects alright so let’s get started all right so the first few videos in this section are going to be on arrays and then we’ll move to object literals all right so arrays are a special type of object in JavaScript they’re also a data structure and they can store multiple values so this is how an array is formatted you can see we have a variable called ARR and arrays are surrounded in Brackets so the values inside of an array are surrounded in Brackets and the values are called elements okay so the each one of these is an element in this array now elements can be numbers they can be strings booleans any data type you can even have arrays within arrays and when it comes to accessing the values or the elements within the arrays we can use the index so arrays are zero based every language I’ve ever used they’re always zero based so they start at 0 1 2 3 and so on all right so I’ll show you how you can access whatever element you want using the specific certified index okay so let’s jump into vs code and start to just mess around with arrays so I’ll go ahead and create an array I’m going to just call it I’ll call it numbers and I’m going to set it to some brackets and in here we’ll just put some random numbers okay and and these it doesn’t have to be numbers I’ll create another one with a different type in a minute but let’s go ahead and console log out numbers and we should see in the console our five values now you also see the index and remember a razor zero base so the first one is always going to be at the zero index now there is another way to create an array object so this right here we just did this is called an array literal okay but we can also use the array Constructor okay just like we have like the date Constructor we used a few videos back where we said new date we can actually do this we can say I’ll call this numbers to actually let’s do a string here we’ll call we’ll call this uh fruits and I’m going to set it to a new array okay it has to be an uppercase a so new array and then in here I can put whatever I want in my array let’s say apple so they’re strings so they do have to have quotes we’ll say grape and orange so either of these are fine right I’ll say fruit console log fruits and you’ll see we get the same type of thing just an array with our with our strings now you’ll probably use and see this more the array literal more than the array Constructor it’s just more concise but you could use either they both create an array object now if we want to access a specific item let me just create a variable up here to Output and we’ll console log X and then I just want to show you how to access a specific item by the index so we’ll say x equals and let’s say numbers and we’ll get the first one so that’s going to be the zero index and you’ll see that’s going to log 12. and I could use this in any expression if I wanted to do like numbers and then get the first one and then maybe add on to that numbers and get the one that the three index and I get 41. I could also use them inside of a template literal so if I put back ticks in here and I’ll say my favorite fruit is and then I can access fruits and then let’s say I want to get the uh we’ll say orange that’s going to be the 2 index because it’s the third one so it says my favorite fruit is we’ll say is an orange all right now there is uh and by the way you can have different types I know these are all numbers these are all strings but I could do this like I could say we’ll call this mixed and I could set that to an array with a number with a string with a Boolean value null so you can put different types in here just to show you that now there is a property on a raise called length and you’ll probably use that quite a bit because there’s a lot of times where you need to know how many items are are in the array so let’s set x equal to we’ll say numbers dot length and if I save that you’ll see we get five if I were to add a new number onto this then we get six okay so that’s how we can get the length now if you want to change of value like let’s say we want to change let’s use the fruits array let’s say we want to change grape to I don’t know pear so we’ll take the fruit and we know that that’s at the one uh two position or two index and then we can set that to whatever we want let’s say pair and then I want to log fruits so I’ll just set X to fruits so if we save that we take a look you’ll see that now pair is in the the two index so arrays are they’re inherently mutable you can mutate them you can change them and also the length property is not read only so we have uh what three fruits but I could say fruits.length and I could say that that’s going to be 2 and if I save now you’ll see fruits only has two so you can do that as well but I’m not gonna I’m gonna comment that out now let’s say I wanted to add on to the end now there’s methods that we can use to do stuff like that and I’m going to show you that in the next video but we could so if we wanted to add a fruit we know that there’s three in there so it’s the index 0 1 2. I of course I could do like three a hard-coded three and I could set that to I don’t know strawberry and then if I log fruits you’ll see strawberries on the end but you’re not always going to know how how many items are in the array also that’s always changing so what you could do aside from using a method which I’ll show you in the next video what you could do is set the index to the length right so if I say fruits.length and then set that to let’s say blueberry if I save that now blueberry will get added to the end and the reason for that is the length is always going to be one more than the last because it’s this starts at zero if we look at the length it’s one two three four five and if I wanted to add one on to the next that would be five right in fact I could copy this down kind of running out of fruits here but let’s say peach and now that will get added to the end okay but but more commonly you’re going to use a method there’s a method called push I’m going to show you in the next video that does the same thing all right so yeah I mean that’s kind of the basics of arrays of creating them and getting the length and and finding the the values by index so in the next video we’ll go ahead and look at some methods all right so in the last video we looked at some array Basics how to create them how to access values by index and so on now I want to look at some of the methods that we can use so let’s create an array you can put whatever you want in it I’m just going to put some random numbers all right and then I’m going to just log out the array so in addition to the values here if we if we go ahead and click this Arrow you see there’s this prototype chain and this has all the different methods that we can use on this array which is quite there’s quite a bit here so obviously we’re not going to go over all of them right now we’re going to go over some of the really useful kind of simple ones just to mutate the array and get values from it and then later on we’ll we’ll look at some of the more advanced stuff including high order array methods so let’s start off with push which will just put a value on the end of the array in the last video I showed you how we could do that using the length property as an index but what you would probably do is just push on to it so you would say array dot push and then let’s say we want to add 100 and now you’ll see 100 gets added on to the end now if you want to take the value off of the very end off the last element then you would use the pop method so array dot pop and we wouldn’t pass anything in because it’s just going to pop off whatever is on the end now you’ll see that 100 is gone okay if we want to do the opposite and add on to the the beginning then we can use the unshift method and let’s say we want to add 99 now you’ll see 99 gets added to the zero index and if I want to take take it off of the beginning then we would use shift so array.shift and now 99 is gone okay we also can reverse the array with the reverse method pretty self-explanatory so now 15 which was at the end is now at the beginning now these methods that we just looked at these are used to manipulate the current array right so when we console log the array after they go through these methods it’s different right now it’s reversed and so on we did add some stuff on but then we took it back off so the next batch of methods I want to show you are ones that we can use to get something from the array either get a value from it or just get some information from it so I’m going to create a variable up here just like we’ve been doing just for our output and then let’s console log that variable and I want to show you the includes method which will allow you to to check and see if a specific value is in that array so I’m going to say x equals and then array dot includes and let’s see if we if we pass in 20 which 20 which we know is in there you’ll see it gives me true so you’re always going to get a true or false from this based on if the value is in there now if we put like 200 which we know is not in there then we’re going to get false all right so the next one I want to show you is index of and what that does is it’ll give you the index of a specific value so if I do let’s say index of and let’s pass in one of these values we’ll do 15. and I save that we get 0. now the reason it’s zero you can look up here and and it’s not zero here obviously but the reason it is is because we ran this reverse okay so the script runs top to bottom so since it’s reversed then it’s put in the zero position so what I’m going to do is just comment out these ones that we did that will that actually change the array just so we’re working with the same array we’re looking at up at the top all right so now if we look at the index of 15 it’s at four if we look at the index of 34 that should be the first one which is zero now if you put something in here that doesn’t exist like 340 you get a negative one okay so a lot of times you’ll you’ll run this through an if statement and just know that if whatever you pass in here is not there it’s going to give you a negative one now the next two I’m going to show you are pretty similar it’s slice and splice and both of them will return selected elements in the array so I’m going to start off with slice and I’ll kind of show you the differences as we go so array dot slice and what this takes in is the first is going to be the start index so where do I want to start in this array let’s say we want to start here which is the one index so we’ll pass that in now if I don’t pass anything else in what that’s going to give me is that value and everything after that as you can see here so 55 and everything after let’s say I want to get just um just 55.95 and 20 so that and the two after so then I would do one two four all right so how that works is we specify the one index and we want to go to the 4 so that’s going to be 1 2 3 and we stop at before the four okay um now this is this is returning this array okay the three that I selected into this x variable it’s not actually changing the array if I log the array in addition to that you’ll see it’s unchanged okay so keep that in mind about slice now splice you can do kind of the same thing but it does manipulate or it does change the original array so if I say x equals array dot splice and the the arguments we pass in or I should say the second argument is a little different the first is the start index just like with slice the second is the number of elements that we want to go over so let’s say I’m starting at one which is 55 and I want to go over four so one two three four I should get 55 to 15. so if I do 4 here and I save now look what we’re logging we’re logging X which is what we basically plucked out one to one and then four over so 55 to 15. now the array that I’m logging only has 34 in it because I basically plucked the rest out okay so slice doesn’t do that it doesn’t change the initial array splice does not only are you taking it out and putting whatever into the variable one one to four but you’re also changing the array so you’re not only getting the values you’re deleting them from the initial array all right now if you just wanna let’s say you just wanna delete one item then you can let’s comment that out so that we have our initial array what you could do is say x equals and then say array dot splice and let’s say we want to get rid of the 20. so we know that’s zero one two three so I’m going to put in the start at 3 and just 1. I only want to take out one and I’ll save that and now you can see we have the 20 in X so it’s set to X and then the array that we’re logging doesn’t have 20 in it anymore because we took it out so that’s how you can remove a single element from an array now the last thing I want to show you is how you can chain methods so I’m going to set X here equal to and let’s just comment out the splice because we know that that that changes our initial array and let’s move this down here so I’m going to set x equal to array and then I’m going to use slice here so slice let’s say one and we want to go 4 over from 1. so that’s going to basically give us again it’ll give us 55 through 15 right if I save this as it is and we look at the console log of x we don’t need array anymore if I look at the console log of x we get 55 well actually it’s I’m sorry I want to use splice if you use slice it’s only going to give you the three because it goes to the 4 index splice will actually go four over and then what I want to do is reverse that so I’m going to do dot reverse and if I save that now you’ll see it gives me that array that splice created and then reversed it if I wanted to change that to a string I could do two string and if I save that now I have it as a string and then I could use a method on a string remember the Char at so Char at you basically put in an index and it will give you that character so let’s say zero save that and I get one okay because the first one was 15 the first number so you can chain on methods like this and it’s not just with arrays as you can see it’s with strings it’s with anything anything that makes sense I mean it depends on what the method returns this splice we know that returns an array and I can run reverse on an array then I can turn an array into a string and then I can get a character from a string if I just run Char at on the Reversed array that’s not going to work it says reverse Char at it’s not a function okay what it really means is it’s not a function on whatever where we’re putting it on if I change that back and it’s a string then it is a function that works all right and you’ll see you’ll see chaining like this all throughout JavaScript so in the next video I want to get a little more uh acquainted with arrays so we’re going to look at things like nesting and concatenation with arrays we’re going to look at something called the spread operator and we’ll go from there all right guys so we’re gonna mess around a little bit more with arrays so I want to look at nesting concatenating and the spread operator and a couple other things so nesting an array is just it’s basically just having an array as an index inside of another array so let’s go ahead and create two separate arrays here I’m going to call this one fruits and we’ll put in here apple pear and let’s do uh Orange all right so that’s our first one and then we’ll do berries and yes I know berries are fruits so let’s say strawberry and blueberry and raspberry so we have two separate arrays now if I wanted to I could take fruits and we looked at the push method in the last video which will add something onto an array and let’s say we want to add on the berries array and then we’ll go ahead and console log fruits and let’s see what we get so we get an array with four items the first three are apple pear and orange and then we added berries which is another array so we have an array within an array so that’s how we can Nest them and you can go as many levels as you want now to access something in a nested array is pretty easy basically we can let’s let’s set this to an output variable so I’ll say let X and then let’s log let’s log X and we’ll say x is equal to and then fruits and let’s say I want to get blueberry which is nested in the the nested array so first of all I want the three Index right because it’s 0 1 2 and then we pushed on as the three index the whole berries array if I just log that what I get is the nested array if I want to get blueberry that’s going to be the one index on the nested array so I would just open another set of brackets and then put a 1 and that will give me blueberry all right now let’s say I wanted to create a whole new array called all fruits and I want to Nest both fruits and berries and we’ll just set X for now we’ll just set it to all fruits just so we can log it out and it’s an array with two items and both items are arrays okay so we just nested those two arrays and if I wanted to access let’s say strawberry I would say all fruits and I want the second array which is at the one index and then I want the first item in that array which is at the zero index save that and we get strawberry all right so hopefully that just helps you understand that you can Nest arrays inside of arrays as many levels as you want if I had a third level I could then access whoops I could access something within that you know so it you can Nest as far as you want now that’s nesting we can also concat arrays which is different it’s not to putting the array inside the array but it’s taking the items from one array and basically adding them into a different array okay as separate items on the same level so to do that we can use the concat method there’s actually a few ways to do it but concat is one of them so I can say fruits and let’s say we want to do Dot concat actually let’s comment this out because I want these to be two separate arrays again and yeah then the rest doesn’t really matter comment that out as well all right so I want to take fruits and then I’m going to concat onto that berries and let’s save that what we get is one single array that has everything from fruits and then everything from berries so the berries here they’re not put in as a as an array a nested array they’re just put in alongside of the rest of the fruits so they’re concatenated just like we concatenate strings with the plus sign we can concatenate array items using this method now that’s one way of doing it the other is using the spread operator and I’ll I’ll have comments throughout this I know I’ve said that a bunch of times I just don’t want to take the time to write comments for everything so the spread operator which is represented as three dots and this can be used with arrays as well as objects in fact you’ll probably use it more with objects and I’ll show you how to do that later but basically what we can do is let’s say we want X and instead of using concat what I could do basically what we did here was we created an array and then we put two arrays inside of it well let’s say I just want the items that are in fruits and berries not the actual array itself then we would use the spread operator with fruits and then the spread operator with berries and now I’m going to log X which is this right here we get the same exact result that we got with concat it just took the items from both arrays and put them basically combined them all right if I took the spread off of berries and I save now berries is going to be an array all right but there’s going to be a lot of times where you you want to take something from one or one array and spread those items across inside of another array so that’s where the spread operator comes in and same thing with objects but I’ll get to that in a little bit now there’s also a method we can use to flatten flatten flatten arrays and what I mean by that is if we have an array that has nested arrays let’s do this one two and then I’ll have another array here with three and four and then we’ll do five and then let’s do another array with six and seven and then eight all right so I have some nested arrays in here right if I set uh if I console log array then you can see that we have two nested arrays in here now let’s say I want to flatten this and just make it all one array that has one through eight for that let’s say x equals and we can set we can do array dot flat and now if I log X and I save that you’ll see now we just have a single array with one through eight so it just flatten this there’s no more nested arrays all right so that’s pretty much it for uh for some of the methods on the array itself now I want to show you some static methods that are on the actual array object um let me just put a comment in here we’ll say static methods on array object and what I mean is if we say capital A array and then dot there’s some methods we can use the first one I want to show you is is array so what this does is it checks to see if something is an array and I’m just going to set this to X so let’s say is array and we’ll pass in fruits and if I console log X we’re going to see true because yes fruits is an array up here if I were to pass in like a string then we’re going to get false so there will be some times where you have data structures that might act like arrays but aren’t quite especially when you get into like the Dom there’s like HTML Collections and things like that where you will you want to check to see if it’s an actual array and this is how you can do it so that is is array the next one I want to show you is from which will create an array from an array like value so if I say x equals and then array Dot from and this again this is pretty useful when it comes to like HTML collections or node lists or whatever but let’s put in here a string of one through five and let’s see what that gives us what it gives us is an array so it takes the string of one through five and gives us an array that has one through five in as an element okay so that’s from and then we also have uh of array dot of which will create an array from a set of values so maybe you have some variables where you want the values to all be inside of an array so I’ll just do this const a equals one V equals 2 C equals three and then I could say x equals array dot of and then we can pass in here A B and C if I save that it’s going to give us an array with one two three so basically just an array of the values of these variables and I know this is this might be a little Advanced for right now you might not be able to kind of visualize what you would use this for yet but I just wanted to throw some of this stuff in here so in the next video I want to test your knowledge or test what we’ve gone over with a couple fairly simple array challenges all right guys so now I’m going to give you a couple challenges and if you don’t get the challenges don’t worry about it I’m not that great at doing challenges where I can’t use resources and stuff like that either a lot of developers aren’t so don’t take it to heart if you can’t do it on your own now the first one I think is pretty easy I think a lot of you will get it so basically I just want you to create an array that has numbers one through five and then I want you to mutate that array using some of the methods that we’ve talked about and turn it into this which is six through zero all right so there’s just a couple methods that you can use I’m not going to give you any hints because this one’s pretty easy I’d encourage you to try to remember the methods rather than go back and look but if you have to look that’s fine too and then the second challenge is to combine or concatenate array one and array two but have the result not have the extra five because if you just concatenate these two you’re gonna have one through five and then you have another five through ten so I want you to concatenate but then take out the extra five and as a hint there’s many ways to do this but you can think of the concat method or the spread operator as well as the slice or splice methods and I’m going to give you two two solutions all right so pause the video now if you’re going to try this out and then just come back all right so let’s go ahead and do challenge one so we’re going to have an array with just one through five oops all right equals and then the result that we want to get is going to be an array that is six five four three two one and zero so that’s what we want the result to be so let’s console log array now there’s a couple methods that we need to use to achieve this hopefully you could remember them and not have to look back but if you did have to look back that’s that’s absolutely fine but we’re going to take the array and there’s a couple ways we can do this and there’s a couple different orders we can do this in so we could reverse it we know that you know this is is counting backwards so let’s say we want to reverse the array if I save that then we get five four three two one now we want to have a zero on the end so we could take the array and then we could push onto it a zero let me save that now we have five through zero and then to add on to the beginning we can use unshift and we can add on to the beginning a six and that’s it so pretty simple now you could have did it in a different order like you could have let’s save that you could have firsted the push so we could push a six on if I save that we get one through six and then you could do the unshift which pushes on to the beginning so you could put your zero and then you could do your reverse like that okay now you’re not going to be able to chain these because like push what that returns is it just Returns the number you push onto it so if I try to like uh if I try to do this some of you might might have tried this you know that that’s not going to work it says unshift is not a function and the reason is because this actually returns a number or it should let me just show you if I were to set let’s say let I’m not going to keep this but just to show you what this actually returns yeah Returns the the number six so you can’t chain those methods all right so that is my solution if you had a different solution and it worked then that’s that’s fine but let’s do challenge two so we’ll go ahead and say challenge two and this is going to be to concatenate these two arrays let’s say array one and that’s going to be one through five and then const array 2 is going to be 5 through 10. and then what you needed to do is concatenate these two arrays but they both have five so you need to get rid of that five and I’m going to give you two different solutions in each each one is in kind of the opposite order so let’s say solution one and I’m going to create a new array called array three and take array one and well basically what I’m going to do is slice that not slice the five out but slice these the ones that I want out and put that into array three so if I say dot slice and remember slice takes in the start index which I want to start at the beginning because I want one through four and then I’m going to put in 4 as the end if I save that oops we need to log this out array 3. if I save that now I have one through four in this array 3. so now what I need to do is basically just add the rest of this on right because I have one through four so I’m going to do that by chaining on concat and I’m going to concat array 2 and if I save that now I have 1 through 10 and there’s no double fives so that’s the first solution the second solution is kind of the the opposite of way around first I’m going to concatenate it so I’m going to say const array 4. and we’re going to use the spread operator here so let’s spread across array 1 values and let’s spread across array two values and if I were to console log array 4 you’ll see I’ll get 1 through 10 but I have my double fives here which I don’t want so then what I’ll do is use splice so I’ll take array 4 and then splice and I just want to take out one of those five so I’m going to start at the 4 index which is 0 1 2 3 4. so right here and I only want to take out one which is that that one so I’m going to put 1 as a second argument and then if I console log or A4 you’ll see I have one through ten and now that 5 is gone so two different approaches they both use different methods but they have they have the same result and you’ll see a lot of that in not only JavaScript but all programming all right so that’s it in the next video we’re going to look at object literals okay so now we’re going to get into another data structure and another type of object in JavaScript which is an object literal so basically these are key value pairs so I have a an example here we have a variable called person and then in curly braces we have just key value pairs that are separated by commas so basically we have the key on the left side then we have a colon and then we have the value which can be a string a number Boolean whatever and these are Keys these are values these are also called properties like this is the name property this is the age property and so on so let’s jump into vs code and let’s start to to work with objects so I’ll go ahead and just create the same one we just saw so we’ll say person and I’ll set that to a set of curly braces and then inside there we’re going to have a name let’s say John Doe and then we’ll do an age of 30. and we’ll do let’s say is admin and that will be a Boolean so we’ll say we’ll say true okay now as far as accessing data from this object first of all is just console log the whole thing see what we get so same thing just the key value pairs we also have our prototype chain which has some methods on it there’s a lot that we can do with objects in this section I’m gonna just go over some of the the basics and some of the easy stuff and then later on we’ll get into more complicated ways of working with objects now to access a specific property from an object we use the dot syntax so I’ll go ahead and actually you know what let’s create our X variable because there’s a few things I want to log out so let’s just do that and then let’s set X to person and then to access the name for instance I can say person.name now we can also use bracket notation so for for example I could say person and then I could use brackets and say I want the age I’m sorry this needs to be a string and I get 30. so this you’re going to see this a lot more the the dot syntax rather than the brackets but you can do it this way now let’s say we want to have an object within an object like maybe an address with some Fields so let’s say address and then we’re going to set that to another set of curly braces and then here we’ll have the street say 123 Main Street and then we’ll have the city let’s say Boston say for the state will do mass now if I want to access let’s say the state what I would do is say person Dot and then the address and then the state if we do that then I get Mass we could also have arrays in here like so if I wanted to do let’s say Hobbies set that to an array and we’ll say music and sports and then if I wanted to access that array I could of course just say person dot hobbies and that will give me the whole array if I wanted to access let’s say the first item or element in the array then I would use of course my my brackets just like I would with any array and that gives me music now we can also update properties so I can say person dot name and I’ll set that to let’s say Jane Doe and then if I log X we’ll just set it to person and you’ll see now the name is no longer John Doe it’s Jane Doe if I wanted to update let’s say is admin I could say person dot is admin or I could use this syntax is admin and what is it to begin with it’s true so I’ll set it to false and then if I log the person we should see is admin as false all right now if you want to remove completely remove a property from an object you can use delete so I could say delete and then person dot let’s delete the age if I do that and I log the object you’ll see there’s no more age now the next thing I’m going to show you is that we can add a function to as a property but I know we haven’t gone over functions so don’t worry about it if you don’t understand this but let’s say person and by the way I don’t think I mentioned you can not only change properties but you can add a new one like if I want to say person dot has children and set that to true and now if I save you’ll see that has children has been added okay so you can add properties as well now like I said about functions let’s say we want to create a function in this property called greet so I’ll say person.greet equals a function and this is just how we Define a function again I’ll get into this very soon and then I’m going to console log here uh template literal and say hello my name is and then I can actually access other properties in here with the this keyword so I could say this dot name and now if I want to call this function I’ll have to do person dot actually let’s just oh we’ll get nah we’ll just do that yeah person dot greet and we need to execute it with parentheses and you’ll see right here hello my name is Jane Doe all right so we we assigned a function to this greet property and we were able to access the name using the this keyword which I’ll talk much more about later now another thing that you can do but I really wouldn’t suggest it is when you’re creating your keys you can use like double more than one word so let’s say I wanted to use first name like first space name I wouldn’t recommend doing this but if you are going to do this then you can just surround it with quotes right so I could say first name and then set that to Brad and then we’ll do a last name so let’s say last space name and now if I want to access let’s say I want to access first name if I try to do this for a space name this is another reason I wouldn’t recommend doing this well right now it’s telling us person has already been defined so let’s change this to person two person two and it’s still going to give me an error because it says unexpected if I’d identifier name now if you’re going to do this again I wouldn’t recommend it using multiple words like this this should be in this form or even this form but if you do happen to come across this and you want to access it you have to use the bracket notation so you would do it like this first space name and you’ll see that will work all right so in the next video we’re going to look more at nesting objects within objects but I also want to show you how to use the spread operator with objects we saw how to use it with arrays but we can also use it with objects okay so now that you know what an object literal is I just want to get into a couple other things including using the spread operator with objects and some of the methods that we can use so and before we do that I just want to show you there is another way that we can create objects let’s say we want to create a to do object now we could do this which just creates an empty object and then we could add properties either in here or we could do like to do dot let’s say ID equals one right and then if we log that out let’s just create our X variable and then if we go ahead and set x equals two to do and we console log X we get an object with an ID of one now another way to do this this is an object literal but we could also use the object Constructor just like we did with arrays so we could say new object like that if I save we’re going to get the same thing so this line this is the same as just setting it to a literal and just an empty set of curly braces and I can continue to add on to this like if I say to do Dot name and we’ll set that to I don’t know buy milk and maybe to do completed not component completed and set that to false okay if we save that we take a look we’re just going to have our properties on that to do object now later on I’m going to show you how we can actually create our own Constructors for certain objects and we could do stuff like this like to do one and then set it to a new to do so you can create a custom Constructor for a custom to do object but we’ll get into that later on now I want to show you how to use the spread operator well actually before that let’s just let’s just go over nesting real quick I know we did in the last video but just to kind of remind you we could set person and then we could have address and then let’s say an address we have coordinates and maybe have a Latitude value of 42. something and then and then a longitude value of negative 71 dot something and then if we wanted to access the let’s say latitude we could do that by setting X to um person then we want to go into address then we want to go into chords and then we want the lat value all right so that’s nesting now as far as the spread operator goes it works very similarly to using it with arrays so what I’ll do here is just create two very simple objects it doesn’t really matter what you have for the Val the properties here but I’ll just do a one be two and then I’m going to create another object 2 and set this for the keys we’ll do c let’s say c 3 and then d 4. okay now if I create let’s say object three I could Nest those in here right so if I just pass in object one and then object two and then let’s just set X to just so we can see it we’ll set X to object three save that now what we have is an object that has two objects inside okay so the first one is object one second one object two now if I want to just take and you’ll you’ll find yourself doing this quite a bit in JavaScript if you want to just take the properties of object one and object two and put them in basically combine them into this single object three then you can just use the spread operator so we’ll just add three dots in front of each one and now when I log out object three we get all of these properties within both objects all on the the top level of object three because we we took them and spread them across all right now if I were to take the spread operator off object two and save you’ll see object one values are are on the top level spread across but object two is in there as a nested object all right so hopefully that makes sense now there’s uh there’s a few methods on the object object that we can use and one of them is called a sign and that does the same thing as the spread operator in fact the spread operator was introduced in es2015 before that you had to use object assign so let’s just say we want to create another object called object four and we’re going to set that to capital O object just like on the array object there’s methods there is here as well and the one we want to look at right now is called the sign so as the first argument we pass in is just going to be a set of empty curly braces that basically just gives us an empty object if I were to log obj4 you’ll see it’s just an empty object now if I want to add the properties from object 1 I would pass object 1 in as the second argument and if I save now you’ll see those are added to this obj4 if I want to take the properties of object 2 I would just add that as another argument save and now those get added okay so whatever I pass in here any objects I pass in here the properties of those are going to get assigned to this empty object okay so both of these lines do the same exact thing and it’s up to you on what you want to use the spread operator to me is easier and more concise and just more modern but if you want you can of course use this Okay so a lot of times we’re going to be dealing with arrays of objects anything any resources in the database like or from an API like to Do’s or users or blog posts you’re usually going to deal with arrays of objects for those resources so so let’s say um should we do here let’s say we want to do an array called to Do’s right so we’ll set that to an array and then in that array we’ll have our first to do so it’s going to be an object we’ll say id1 and then name we’ll say I don’t know buy milk again okay and I’m going to put a comma after that and copy it down a couple times and the second one second object is going to have an ID of 2 this will have an ID of three and here we’ll say I don’t know pick up kids from school and then we’ll have take out trash okay so now we have an array I’m yes an array of objects I’m going to set this x here to to Do’s if I do that we’re going to see our array of objects now if I want to access a specific object just like we do with any array we use our bracket syntax say we want to get the first one we use our zero index that gives us that object now if I want to access specific property like name I simply do dot name all right so those are arrays of objects now later on we’re going to get into iteration and looping and being able to you know go through each object and and do something to it or just display it but we’re gonna we’re gonna do that a little bit later now I want to show you a few other methods we have available on object so if you want to get all of the keys in an object and put those into an array we can use object keys so let’s say x equals object dot keys and what do I want to use this on let’s do the the to do object we created up here so say object dot keys and we’ll pass in the to do object and then we want to log X and you’ll see now we have an array that has the value of ID name and completed okay so it just took the keys from this to do object and put them into an array now there’s going to be times where you’re going to want to get the length of an object meaning how many you know how many properties does it have in it and we can’t use length on that like if I try to do x equals and let’s take our to do object and do length if I do that it’s going to say undefined so the way that we can get it is by first getting the keys and then getting the length of that so if I just take this and put that on there that’s going to give me an array right and we can use length on an array so we’ll simply do length and if I save we get three okay so up here you can see we have three and and I could have created an object literal as well so the next thing is uh if you want to get an array with all the values just the values we can use object.values just like we can use object dot keys so let’s say object dot values and we’ll pass in to do save that and now we just have an array of the values now if you want to get an array of the key value pairs you can do that with entries so let’s say x equals object Dot entries and then pass in our object save that and now we have an array with arrays that have the key value pairs and then the last one I’m going to show you is has own property which will give you a Boolean indicating if the object has a specific property so let’s say x equals and then we actually call this on the the actual object so for instance to do and then we can say has own property and let’s pass in name if I save that we get true because it does have a name property right if we put in I don’t know age and I save that then we get false because that to do object does not have a property of age so that’s it I just wanted you guys to get familiar with the spread operator and some of these these really helpful methods that you have on on your object so in the next video we’re going to look at something called destructuring and also naming because you do have a lot of properties inside of an object and sometimes you might not you might not want to do this because it’s pretty long I’m going to show you how you can destructure so that you don’t have to do as as many you know as much as this dot notation so we’ll get into that in the next video okay so now I just want to show you a couple things that you can do as far as naming and and destructuring variable names from object literals so first off if you’re creating an object where the key and the value are the same if the value is a variable then you don’t have to add both so let me show you what I mean if we have these variables here and let’s say I want to create an object so we’ll say const person and let’s say I want to set name or not name first name and I want to set that to the first name variable right so you would do that and then I’ll just copy that down and this one will be last name and this one last name and then we have our age okay so now if I come down here and do a console log of person Dot age and save that of course I get 30. so I’m setting the key of first name to the value of whatever is in the variable of first name if you do this and these are the same you don’t need to add the second one you don’t need to add the value you can simply do this get rid of the colon as well and now if I save that we still get 30. so it saves you some typing and uh and I just wanted to show you this because most most JavaScript developers will do this there’s no sense in in repeating yourself if you don’t have to so the next thing I want to look at is destructuring so basically what we can do here let’s say I wanted to get well let’s create another object so we’ll create a to-do object with an ID and let’s say title take out trash so if I want to create a variable of ID with the ID of that to do I could do this you know I could do that and then console.log the ID but what we what we can do is destructure properties from the object so we want to set this equal to the object itself and then any properties we want to extract or destructure are going to go into these curly braces so if I save that you’ll see I get one I get the same thing if I want to take out the name I can do that as well so you you can well let me log it so you can see so you can think of this as I’m sorry not name title the title and title so you can think of this as as pulling these variables out of the of the object and you can go multiple levels deep like let’s say we have a user in here and that’s an object that has a name so if I want to get that if I come down here and I destructure user I’m just going to log that for now and save that and you see that it’ll pull out the object to use this entire user object if I want to get the name or any other property what I could do is put a colon here open up another set of curly braces and we want to take the name from the user so now if I come down here I should be able to just console log name now another thing we can do is rename Properties or keys so let’s say I’m destructuring ID but let’s say I want to rename it to to do ID if I want to do that I can put a colon and then just do to do ID like that and then if I come down here and I console log to do ID I get one okay so this and this might might be a little confusing just keep in mind that when you use the curly braces you’re destructuring if you don’t then you’re just renaming now we can also destructure arrays and I know we’re talking about objects in these in the last few videos but I figured it’s relevant here to show you this stuff even though it does have to do with arrays so I’m going to create an array called numbers and we’ll set that to just whatever 33 and let’s do one more okay and I just want to put a comment here that we can destructure arrays oops that should be a comma all right so the way that we do this is we create variables for starting at the beginning for the first second third and so on all right so let’s say const and then the way we destructure arrays is going to be with brackets okay objects we use curly braces and arrays we use brackets we’re going to set that to the array name which is numbers and then in here I’m going to say first and second so what this will do you’ll see if I console log first and second it’s going to give me the first two elements the first two values in the array 23 and 67. and of course if I if I put third in here that would be the next one 33. now if you want to get the rest of the numbers and put them into a variable as an array we can use What’s called the rest operator now it’s a little confusing because the rest operator is is the same as the spread operator it’s the three dots but in this use case it’s often called the rest operator and the way we use that is instead of just putting third which would just get the next one we would do three dots and then a variable name oftentimes called rest and then what I’ll do here is log first second and rest now what you’ll see is we’re logging the first and second 2367 and then rest contains an array with the rest of the values in that array in this case is 33 and 49. if I put in 52 here and save that’s going to get added to the rest array and just to show you I can change this to anything I’ll just say we’ll say nums and then if I come down here and I do nums that’s going to give me the same thing but I’m just going to put that back to rest okay so I know it’s a little confusing spread operator rest operator it’s just when you use it in this instance or in this use case then you might see it called the rest operator all right so that’s it in the next video I want to talk a little bit about Json okay so since we’ve been talking about JavaScript objects I think that this is a good place to introduce Json okay which I get a lot of crap for saying it that way a lot of people say Json I say Jason but it really doesn’t matter it’s j j s o n now Jason is something that you’ll be working with a lot as a JavaScript developer and it stands for JavaScript object notation and it’s a lightweight data interchange format so it’s essentially a way of storing data in a simple human readable format now in web development especially in JavaScript we work a lot with with apis and you know apis to send and receive data to and from a server and several years ago XML which is extensible markup language was kind of the standard for sending data or getting data from a server but in recent years Jason has become the stand standard so you’ll very very rarely work with XML these days now Jason the syntax is very similar to JavaScript object literals which is what we’ve been working with now to give you kind of an example of an API that you may work with as a front-end developer you’re going to work with backend apis where you hit you know a URL and you fetch some data or you post some data and we’re going to get into all that later on apis and you know rest apis and stuff like that now just to give you an example GitHub has has a public API that we can use so I’m going to go to one of the URLs just to kind of show you an example of of some data we’ll get back so if we go to it’s actually API api.github.com and then we can go to slash users if I do that will get an array of like I think I think it’s like the first 20 users of GitHub so as you can see it’s an array of Json objects which are very similar to JavaScript objects right we have key value pairs now the difference here is that the keys are going to have double quotes around them as well and with JavaScript object literals we don’t have quotes around the keys and you have to have double quotes around the strings here as well numbers you don’t have to but strings you have to have double quotes around or it’s not going to be valid Json but this endpoint here API github.com users is an example of something you’d hit with with the fetch API which we’ll learn about later and you can make a request and get this data and bring it into your application you could even do user slash and then your username so I’ll put mine in here and then that gives me some information about my account my login my ID number it even gives me some other API URLs that I can hit to get other things all right so for example uh is the repos so this repos URL if I were to hit that end point I get an array of all my GitHub repositories okay so as Json objects so I just wanted to kind of show you an example of an API that gives us Json data now you can also have Json files like if I create a new file here and I’ll just say I don’t know to do dot Json the way that I would do this it usually a Json file is going to have an array of Json objects so you would have brackets just like in JavaScript and then each object would have curly braces but your keys have to have double quotes as well so say id1 this could be a number or a string and then let’s say title title say take out trash now vs code will automatically validate this like if I take those quotes off it’s going to give me an error if I hover over it says property Keys must be double quoted because it knows them in a Json file okay and then there are websites where you can validate Json as well you just paste it in and it will tell you if it’s correct but yeah it’s pretty much just a JavaScript object with some double quotes so what I want to do as far as JavaScript to show you how we can convert our objects to Json and the other way around so let’s create an object here let’s do something different we’ll do like uh which we do we’ll do posts like a blog post and we’ll set that to let’s say title say post one and this is just a JavaScript object literal so title actually let’s put an ID to so we’ll say id1 and then let’s put a body and I’ll just say this is the body okay so we have a JavaScript object right I can console log that post and if I want to convert this to a what we call a Json string there’s a Json object we can use so let’s say cons string so this Json object has a method called stringify so just stringify and Par so the two methods you’re going to be using quite a bit when dealing with this so stringify will turn an object into a Json string so I’m going to pass in here post and then let’s log Str and and notice it’s formatted differently it doesn’t have like the collapsible arrows and stuff like that it’s just a simple string okay and this is what you would send if you were sending data to a server this is what you would send okay now when you use like the fetch API or other libraries to make HTTP requests a lot of times it does this for you like you you can just send the post like this and it will automatically stringify it where you do end up using stringify and parse the next one I’m going to show you is with local storage and local storage is a way to store things on your client on in your browser and they can only store it can only store strings so you can’t store like an object like this so what you would do is stringify your object put it into local storage and then when you take it out you would parse it back into an object and we’ll we’re going to get all into local storage later so now that we have a Json string in the Str variable let’s parse that Json so we can do that and I’m going to put this in a new variable called obj and we’re going to set that to Json dot parse and then we’re going to pass the string Json string in there and then let’s go ahead and log obj and we’re going to get our initial post object literal okay so these are the two methods that you’ll be using quite a bit when dealing with this type of thing and then it doesn’t have to just be a single object it can be an array as well so if we say const let’s say posts and we set that to an array of objects I’ll just grab this one here and paste that in then we’ll put a comma and we’ll create another one and I’ll just change that to a 2 and we’ll say post 2. so now we have an array of objects let’s say down here const str2 and we’ll set that to Json Dot stringify and let’s pass in our posts and then if we log str2 you’ll see we have a Json string that has a couple array a couple arrays a couple objects inside of an array now one thing to keep in mind is if you have a Json string like this this Str right here you can’t take that Json string and then try to access like let’s say ID okay if I do that I’m going to get undefined all right if you need to access a specific property you first need to parse it so if I console log object dot ID that’s going to work but yeah I mean that’s that’s pretty much it as far as using JavaScript to parse Json strings or turning JavaScript objects into Json strings so in the next video we’re going to have just a pretty simple object challenge for you guys and then we’ll move on to functions and scope and things like that all right guys so I have a a challenge here for you that has to do with object literals and it has multiple steps but don’t get overwhelmed because it’s it’s pretty easy for those of you that already know the basics of JavaScript will have no problems with this but we’re going to take it step by step so I’m going to read step one you can pause the video and do it I’ll do it and then I’ll go to step two step three Etc so step one is to create an array of objects called Library so have a variable called Library set it to an array have three objects inside with the type the properties of title author and Status title and author Should Be Strings whatever you want whatever book title and author and then status should be another object so a nested object with the property of own reading and red which should all be Boolean values okay so do you if you own the book if you’re reading it and if you’ve read it so for all status set own to true and then set reading and red to false so basically you just need to construct an array of objects so pause the video now and go ahead and do that and I’m going to do that now as well so I’m going to create a library array here and then inside it says to do three objects with properties of title so I’ll just put that for now and then we also want author which is going to be a string and then we want the status which is going to be a nested object and status is going to have own which we want to set to true it’s going to have reading which we set to false and then red which we also set to false okay so I’m going to just copy this because we want three of these okay so we just want to make sure we had three and you can put whatever you want for the titles and authors I’m going to say the road ahead I’m just putting anything here and this is by Bill Gates and then we have the Steve Jobs biography by Walter Isaacson I think that’s ice palette and then we have Mockingjay and that’s by Suzanne Collins okay so here’s step one right we just created an array with three objects with the property specified so now let’s move on to step two so you finished reading all the books set the read value for all of them to True do not edit the initial objects at the values using dot notation so don’t just go in and change red to True here we’re going to come down here and set all of the the red values to true so you can pause the video and do it yourself but this is going to be pretty simple basically we just want to say library and there’s there’s multiple ways you could do this you could Loop through it but we haven’t gone over Loops or anything so let’s say library zero and we want to set status right and then we want to set red to true and we’re going to do that for all of them so let’s say one and two as well and then we’ll just go ahead and do a console log of library and if we take a look we should now see in status that read is true for all of these so read is true and status read is true so that’s step two step three is to destructure the title from the first book and rename the variable to First book so we went over destructuring and naming a couple videos back so let’s do that we’re going to go let’s just put a comment here and pause the video if you’re gonna do it on your own and say step two and this is step one okay so step three we’re gonna destructure so from the what was it the first destructs of the title from the first book and rename it to First book so we know the destruction object we use curly braces and we want to set this to the object name which is Library we want to destructure the title right so I’ll say title and then let’s console log title actually I’m going to get rid of this console log right here so I’ll save that we get undefined and that’s because we’re in an array it’s not a single object called Library so we want to get the first the first book if I save that we get the road ahead now to rename this variable we just use a colon so we can say colon and we’ll say first book and then we should be able to console log the first book variable and get the road ahead so that’s step three so step four is to Simply turn the library object into a Json string so you can pause the video and do that and that’s pretty simple say step four so we want to we’ll create a new variable we’ll call it Library Json and then let’s set that to Json Dot stringify and we want to pass in the library object and then we’ll go ahead and console log Library Json and now we should have our library as a Json string all right so that’s it I know that was pretty simple for those of you that already know JavaScript Basics but if you didn’t then hopefully this helped you out so in the next section we’re going to go ahead and start looking at functions and scope all right so now we’re going to start to get into functions which are really important part of any type of programming because you can create blocks of code that you can run anywhere and at any time so we’ll look at creating basic functions we’ll look at function declaration versus Expressions we’ll look at Arrow functions something called iffes or immediately invoked function Expressions we’re also going to look at scope which is really important in programming because this lets you know what what context your code is being run in if it’s the global scope or if it’s within a function scope or another type of block scope and then we’re also going to look at things like the execution context and the call stack which are might seem a little Advanced but like I said I want you to not only learn the syntax but understand kind of what’s going on under the hood in the browser what’s actually happening and execution context is something that I think you’ll benefit in learning now rather than you know two years down the road so it’s just the last I think two or three videos we’ll be talking about that stuff and you’re not gonna need to learn any any advanced code or anything like that in fact we’re going to look at very very simple code but just look at what is actually happening behind the scenes with the execution context with the call stack and so on all right so that’s it let’s go ahead and get started on functions all right so now we’re going to talk about functions and scope and I know a lot of you already understand functions and and that’s fine but I do want people that are new to JavaScript and new to programming to basically be able to start from scratch and learn what functions are and how to use them so let’s get started with some of the basics so first of all a function is it’s a way to group code together that you can run later you can run at any time and as many times as you want and it’s a way to make your your code more readable and easier to understand so to create a function there’s actually multiple ways and I’m going to show you multiple ways but for now we’re going to do kind of the the basic way to create a function and that’s using the function keyword so after that we can give a function any name we want let’s say we want to call it say hello and then we need to add in our parentheses okay now in the curly braces here is where the function body goes this is this is the code that will run when we run our function so I’m just going to have this function do a simple console log of hello world all right now if I save this nothing is going to happen because all I’ve done is defined or declared the function I haven’t run it to run it we have to put in the function name and then a set of parentheses so if I go ahead and save that and run it you’ll see that it’ll console log hello world so that’s that’s the absolute simplest function that you could write now when it comes to passing data into a function we do that with parameters okay and and there’s a difference between parameters and arguments a lot of times they’re used interchangeably which I think is fine but just to be really specific when you’re declaring a function like let’s say we have a function called add and when we’re putting in here the variables that we want to be able to be passed in like let’s say we want we want X and wire let’s be a little more specific we’ll say num1 and num2 so this function takes in two numbers these are the parameters okay that the function can take and then what I’m going to have this function do is just console log num1 plus num2 so it’ll evaluate that expression and log it to the console now when I call this function so I say add and then I pass in the numbers that I want to add let’s say 5 and 10. these are arguments okay when you’re declaring the function these are parameters when you pass in an uh a value here these are arguments but again people will say I’m passing in a parameter of five and I think that’s fine I’m not like you know one of those sticklers and just to be clear on the kind of the vocabulary when we run a function like this this is invoking a function or calling a function when we do this this is defining or declaring a function now most of the time when we create functions we’re returning some kind of value these particular functions that I just created they’re not returning anything they’re just simply doing a console log but usually we’ll return something so to give you an example let’s say function and we’ll call this subtract okay and this is going to take in again let’s say num1 and num2 and I’ll get to scope but just know that these variables even though these are the same it’s okay because they’re function parameters of in different functions so I can use num1 here and here I couldn’t use it like in the global scope I couldn’t create num1 and then create num1 again so in here let’s go ahead and return we do that with the return keyword and we’re going to return X not X num1 minus num2 now I’m going to go ahead and invoke this by saying subtract and then I’m going to pass in let’s say 10 and 2. now if I save this we don’t see anything in the console because we haven’t done any kind of console log what we did is returned uh the the result of this expression now I’ll get into why we return values in a second but just know that anything we do under this like let’s just console.log we’ll say after the return if I go ahead and run this you we don’t see the console log that’s because we’ve already returned we’ve already exited the function so it’s not going to run anything after an in vs code you can see it’s kind of a lighter lighter contrast now the reason we return something is because we want to do something with that value so in this case let’s say we want to put it into a variable so I can actually set let’s say right here we’ll say const and then say result equals subtract 10 from 2 or I should say 2 from 10. and then I can do what I want with that result so I’ll just console log it I’ll say console log result and now I get 8. I could also just console log the function I could say subtract and let’s say I don’t know 20 and 5. if I save that I get 15. all right so instead of console logging from here this this is going to hold whatever the value is it’s returned and there might be cases where you return with no value you just write return and that’s good for like um let’s say you’re you’re sending a request to a backend or an API and you’re updating something in a database and you’re not you don’t actually need to return anything you might just return with no value all right now in the next video I want to talk more about arguments and parameters I know I mentioned them here and and showed you you know the basics but I want to talk a little bit more about that in the next video all right guys so in the last video we saw that we can create functions and we can allow data to be passed in by creating parameters or params and then the data we pass in when we invoke the function are called arguments so I want to look a little more into that so let’s create a function here we’ll call it register user and let’s say it takes in a user which right now will just be a string and then I’m going to just return from this let’s say user and then I’ll just concatenate on and say is registered obviously in real life you would you would connect to a database and insert a user in this now but this is just for for example so we’re going to return that string and then I’m going to just console log register user and we’ll pass in a string of John and then in the console you can see we get John is registered okay so created a parameter of user we pass an argument of John now first off if it’s not obvious this user variable right here this is not available outside of the function it’s in what we call the function scope and I’m going to talk more about scope in a video very soon but just to clear that just to show you that if I console log user it says user is not defined so out here in the global scope it doesn’t see that user variable now if I were to console log register user without passing anything in even though I defined user you can see I get undefined as user because remember a variable that hasn’t been defined it has a data type of undefined and a value of undefined so what we could do to have a default value there’s actually a couple ways we could do that um the old way before es2015 actually let’s go in here was to have an if statement I know we haven’t gone over in conditionals yet but this is pretty simple we would just say if not remember the exclamation is basically the opposite so we could say if not user whoops meaning it didn’t get passed in then we could take that user variable and assign it so let’s call it bot and now if I save that and we run it you’ll see it says bot is registered now with the es2015 or es6 update there’s an easier way to have default parameters because you don’t want to have to do this for every parameter that you have so let’s comment that out and then up here what we can do is simply say user equals and then set it to whatever we want as the default and now ICDC bot is registered okay if I had another variable and I wanted to set it to a value I could do it just just like that just adding the equal sign so that’s default parameters let me just put a comment here so default params and then the next thing I want to show you are rest rest parameters and if you remember a few videos back when we looked at the structuring I showed you with arrays you can destructure values into variables and then you could use the rest operator to basically put the rest of them into an array and you can do kind of the same thing with your parameters or with your arguments so let’s create a function here we’ll call it sum and I’m going to use the rest operator here with a variable called numbers and that can be called whatever you want and then let’s just do uh I want you to get used to using return so we’ll just return from here numbers and I want to see show you what we get now since we use return we do have to just console log the function so we’ll say sum and then let’s pass in one two three and see what we get so it gives us an array with all of the arguments that we passed in okay and I could pass in just as many as I want here and it all gets put into an array called numbers okay a function scoped array called numbers now I know we haven’t gone over like for Loops or anything but I just want to show you that we could use a for Loop to take all the numbers that are passed in and then add them together so let’s go ahead and just initialize a variable here called total and we’re going to set that to zero and then I want to Loop through again I’ll I’m going to go over four Loops in depth later but let’s say const num so we’re going to say num of numbers so basically for each one of the numbers we’re going to call it num and then I’m going to take that total variable and I’m going to use the plus equals here so that I can add num onto each one after every iteration and then I’m just going to return the total okay so now if I console log sum and pass in one through five I get 15 because it’s just adding them all together okay if I add 6 21 if I add 100 121 and again this the body doesn’t matter I just want you to understand you can basically pass in unlimited number of arguments using the rest operator and that those all get put into an array all right now you’re not always going to get primitive values passed in as arguments in fact more often than not you pass in objects and arrays and stuff so let’s say objects as params and we’ll do we did register let’s do login user and say it takes in the user but this time it’s going to be an object so obviously you could use any of the properties that are on that object so for instance we could do a console let’s do a we’ll do a return so we’ll say return and I’ll use a template literal here and let’s say the user I guess yeah we’ll just put the user and let’s say that user has a a name property with the ID of and then we’ll do user dot ID is logged in okay and then down here what we could do is we could pass it in a few ways we could put it into a variable like this and we could give it an ID and then a name and then we could call login user and we could pass in that user and if I save actually we returned it so we need to actually console log it so if I do that we get the user John with the ID of 1 is logged in okay or you could pass it in let’s do another console log you could also just pass in like this let’s put the object and let’s say id2 and name Sarah and then we get the user Sarah with the ID of 2 is logged in so we can also pass in arrays let’s say arrays as params and now I’m going to actually create a function finally that’s semi useful so we’ll create a function that will get a random number from a specific array that we pass in and if you want to pause the video and try this on your own you can because we’ve already looked at how to get random numbers and stuff like that so you can do that if you want but I’m just going to create a function called let’s call it get random and it’s going to take in an array and then first thing I’ll do is is generate a random index for the array for the element that we’re getting because remember we access the element through indexes so let’s say random index and we’ll set that to math dot floor so we’re going to round down remember this from a couple sections back so we’re going to round down a random number let’s say math dot random that gives us a decimal between 0 and 1 so we want to multiply that by the length of the array okay so this is all stuff that we’ve looked at so that will give me a random index now I’m just going to create a variable called item and set it to the array and then the index is going to be random So Random index we want to use that here okay and then we’ll just return or we’ll just console log the item okay and then let’s just call down here get random and we just want to pass in an array and you can put whatever numbers you want in here we’ll do one through ten and you’ll see 9 if I reload 9 10 3 10 8 . so yeah it’ll just generate a random number that you pass in now remember the the the rest parameters that will give you an array of anything you pass in so another thing we could do here is just add on that and then automatically whatever we pass in gets put into an array so I could actually get rid of the brackets here and save and I should get the same result which will give me a random number between any of these numbers I pass in and I didn’t need to pass in an array because the rest rest operator will turn whatever I pass in into an array but I’m going to put it back to how I had it just because this is supposed to be showing you how to pass in an array all right cool so in the next video we’re going to look start to look at scope okay so in this video we’re going to talk about scope and in particular Global and function scope now scope it’s an important Concept in JavaScript and it refers to the current area or the context of a specific piece of code and there’s certain rules for what we can access in specific Scopes now global means just what it sounds like it means that your your Global variables are going to be accessible from absolutely anywhere in fact the browser has a window object if I go ahead and type in window in the console we’ll see the window object here that has a ton of methods and properties that we can access from anywhere whether we’re just in our Global page scope or if we’re in a function or in a block or whatever in fact alert the method alert is on that window object if I say window dot alert and I pass in here let’s say hello and I save that and run it then we’re going to see that pop up now since window is the the top most object it’s at the top level we don’t even need to do the the window dot we could just do alert which is what you’ll usually see okay um and then there’s other things like for instance we can do window dot inner width and that will give us the browser’s inner width so you’ll see down here it’s logging 455. and again we don’t need window but in this case on something like this on inner width I would keep the window but it’s it’s really preference but just to show you I could do it without it all right now we can access these these window object properties and methods from anywhere if I were to create a function and say run and then run that function and in here do let’s just do console log we’ll do window dot let’s say inner height which is another property if I do that it’s going to show down here my my window height is 136 and it’s measuring from here to the to the console all right now as far as creating our own variables in the global scope that’s really what we’ve been doing if if you’re creating a variable that’s not in a function or in a block or anything that’s in your Global scope so let’s say x equals 100 and obviously I can access it from the global scope if I do X I’m just going to also put a string in here that says we’ll just say in global save that we’re going to see 100 and in global now since that’s Global I can also access that in functions so I’ll say console log X and let’s say in function save it and you can see we can access it there as well if I have a block like an if statement which I know we haven’t talked about yet but just to show you real quick if I say if true so since I put true whatever I put in here is going to run I’ll do a console log of x and I’ll say in Block save that you can see we’re accessing it from there as well now functions have their own scope so what I’m going to do here is create another function called add and in here obviously we can access X I already showed you that we can create variables in our functions so we’ll say const Y and we’ll set that to 50. and then I’ll do a console log of Y and what we have to run it so if I save that and run it you’ll see that we’re logging Y which is 50. now since I defined this variable inside the function this is function scoped okay this is not a global variable if I go outside the function and I try to log y I’m going to get an error it says Y is not defined because it’s looking in the global scope it’s not going to go into this function and pull out variables and allow us to access them and of course since I created this this variable Y in this function I can’t go in this function and do it here either right if I do that now this error is running you can see at line 11 and that’s where I just did this console log all right so I’m just going to undo that and I’ll comment this out to get rid of that error now I can access the global variable X inside of any function I want so if I were to go right here let’s say console log X Plus Y and I’m going to get 150. all right now if I were to in this add function create a variable called X if I do that and save you’re going to see now we get 51 it’s adding this X and this y so what this is doing is overwriting the globally scoped x value and this is called variable shadowing now when you hear the term local scope that’s just that just refers to whatever scope you’re in whatever you’re talking about if we’re talking about you know this y variable right here then our local scope is this add function scope if we’re talking about this one then where the local scope is the global scope all right now that is global and function scope in the next video even though we haven’t gone over like if statements and loops and stuff like that which are blocks I think this is a good place to talk about block scope all right so we talked about global scope and function scope now we’re going to talk about Block Level scope and I’m also going to show you some of the differences between using VAR to create variables versus using Latin const because VAR is not Block Level scoped so I’m going to create a variable in the global scope called X and then I already showed you this in the last video that if we have a conditional which is a block and we try to access a global variable that’s fine right because Global variables we can access from anywhere now if inside of this block I create a variable let’s say Y and set it to 200 of course from here I could do like X Plus y that’s going to work but if I come out here and I try to do X Plus y that’s not going to work because y has not been defined on the global scope it’s defined inside of this block so it belongs to this block so I’m going to comment that out and I’m going to show you how this would work with VAR in a second but first I want to show you a loop example so you don’t have to understand for Loops yet to really see what I’m talking about here but I’m just going to create a simple for Loop I’m going to use let I’m going to say let I equals zero and then we’ll say as long as I is let’s say less than or equal to 10 and then we’re going to increment by 1 and then here I’m just going to do a console log of I so if I save that what it’s going to do is just start at 0 and it’s going to Loop through and console log each number until it gets to 10. so for very simple for Loop now if I were to come outside of this and do console log I you’ll see I’m going to get an reference error I is not defined so I is is scoped in this Loop in this block now I want to show you the difference between VAR versus Latin cons so I’m going to create a block here just an if statement and just say true and let’s create a cons variable of a so we’ll set that to let’s say 500 let’s say let B we’ll set that to 600 and then let’s use VAR C and set that to 700. okay now if I come outside of that block and I console log a we’re going to get an error by console log B we get an error and if I console log C it works you’ll see 700 so that’s the big difference between VAR versus let and const VAR is not block scoped so if you have a variable that you created with VAR inside of an if statement that can that’s accessible from outside and that’s not really good that’s not what you want you want your variables to be block scoped that’s how most programming languages work so in es2015 or es6 they decided to create let and const but of course you can still use VAR because if they they took VAR out that would break a lot of projects so yeah I would always say use Latin const now even with loops if if I used VAR here instead and then I come down and uncomment this console log I you’ll see that it’s actually giving me 11. so it’s not throwing any type of error it’s working and giving me 11 which obviously I don’t want that to happen now VAR is function scoped so I want to make sure that I explain that so if we come down here and I create a function called run and then in here I say VAR let’s say I don’t know D and set that to a hundred right so obviously I can use that here I’ll say console log d and of course I have to run the Run function and now at the bottom you’ll see a hundred and then if I try to come outside of here and console log d I’m going to get an error even though I use VAR because VAR is function scoped okay if you can’t access a VAR variable that’s inside of a function outside of a function but you can with other blocks like loops and and if statements now there’s one other thing that I want to mention about VAR so let’s say we have let’s say const Foo equals one and then let’s say VAR equals two so when we set a global variable with VAR let me just comment that out get rid of that error when we create a global variable with VAR if we look at the window object let’s take a look here you’ll see that it actually gets added to the window object when we use letter cons that does not get added to the window object so you can see here there’s no Foo so that’s another kind of difference between constant Latin VAR and you’re probably not going to want your Global variables on the window object all right guys so now we’re going to look at how scope works with nested functions and nested blocks now nested functions relate to something called closures and we’ll look at ways to use closures later on but I think it’s a bit too early to to learn them a lot of people are intimidated by them but we can at least look at how Scopes work with nested functions so let’s go ahead and create a function I’m going to call it first and then in first we’ll create a variable called X set it to 100 and then what I can do here is Nest another function so I’m going to call this one second okay so it’s nested inside first and here we’ll create a variable called Y and set that to 200 and then in second I’m going to console log X plus y now in order for a second to run I have to call it within first right so we’re going to run second here and in order for first to run I have to call it here so I’m going to go ahead and save that and you’ll see I get 300. so you can see I can access from the parent function from I should say from the child I can access any variables that are in the parent scope however it doesn’t work the other way around I can’t access from the parent variables in a child scope so if I if in first I try in console log y then that’s going to give me an error okay so remember you can access parent variables but you can’t access child variables so they’re two separate Scopes now it’s very similar with blocks so let’s go down here let’s say if we’ll just say if true and then in here I’m going to say const x and I’m on a different scope so I can use x and then let’s say we have another if a nested if and here we’ll say if x equals 100 and again I know we haven’t gone over if statements we’re going to get to that soon I just want to show you this this is kind of the same type of thing where we have let’s say Y and we can console log here um let’s say X Plus y and if I save that we have to comment this out because it’s giving us an error if I comment that out you’ll see we get 300 right because I’m able to access here I’m able to access the parent Scopes variable of X but if I go outside of this this child if or this nested if and I try to console log Y which is created in there then that’s not going to work okay because this is a separate scope that I can’t I can’t access but you can access the parent from within the child so hopefully that makes sense I know it’s a little confusing but I figured this was a good place to mention this since we’re talking about scope okay so up to this point we know how to declare functions and invoke them or call them or execute them however you want to put it there is another way that we can create functions and that’s with a function expression so let’s first declare a function just like we’ve been doing so I’ll say function this is called a function declaration right so we do that by just putting the function keyword first and then let’s call this add dollar sign and what this will do is take in a value and then just prefix it with a dollar sign so we’ll return from this a string with a dollar sign and then we’ll just concatenate the value and then if we want to invoke it we can just well let’s let’s do it in a console log since this is returning so we’ll say add dollar sign and let’s pass in here 100. so if I save that we get 100 so that’s a function declaration we start off with the word function and then name it and so on but we can also use a function expression where we actually create a variable so let’s call this add plus sign same idea of it with a plus sign and we set that equal to a function and that will take in a value and then we’ll go ahead and just return we’ll do a plus sign and then we’ll concatenate the value and then if we want to invoke it we can do a console log and say add plus sign and let’s do 200 and if I save that we get plus 200. so notice that we invoke them the same exact way we just call the function pass in a value but they’re declared differently the the expression is just a variable it’s a function assigned to a variable now in JavaScript you don’t have to use semicolons they’re optional but notice at the end of the expression we do have a semicolon we don’t add a semicolon to the end of a function declaration now there are some differences here and it comes down to something called hoisting now I’m not going to really go into hoisting as far as how it works right now I’ll do that later when we talk about something called the execution context but in very simple terms hoisting is the process of moving all the function and variable declarations to the top of the current scope before the code is run so you can think of it before your code is actually executed you can think of a step before that where it goes through and it looks for all your func function declarations and your expressions and your variables and puts it all at the put puts all those at the top of the page now even though this happens only function declarations are available before the code is executed so let me show you what I mean if I take this right here where I’m calling add dollar sign and I move it up above which whoops where it’s actually declared and I save that it works which might seem a little weird because we’re calling add dollar sign before we actually defined it so how does it know that and the reason for that is hoisting because again there’s you can think of it as a separate step before your code is actually executed where this is moved up top now like I said only declarations are available before the code is executed so if I do the same with an expression if I take this console log and I move it above where we where uh where we Define it and I save that it says uncut reference error I cannot access add plus sign before initialization okay so when you use a regular function declaration you can call it beforehand if you wanted to put all your functions at the bottom of your script you could do that although I really wouldn’t recommend it I think it’s much cleaner to have your functions declared or defined and then use them but uh but yeah I just wanted to go over declaration versus expression in the next video we’re going to look at another type of function expression and that’s Arrow functions so Arrow functions were introduced into JavaScript in 2015 they were part of the es2015 or es6 update and they there’s some advantages to using Arrow functions of course they’re more compact they also have an implicit return which I’ll show you and they also have a lexical scope which I’ll talk about a little later so let’s start off here by just creating a regular function declaration like we’ve been doing so just a simple add function that will return a plus b and then we’ll call that we’ll just do a console log of ADD and pass in one two so we get three now let’s let’s rewrite this as an arrow function so I’m going to go right underneath it and we’re going to say const add and remember in the last video I showed you we can also create function Expressions so I could do equals function like this now an arrow function we can actually get rid of the function keyword and then instead of using the function keyword after the parentheses we’re going to use an arrow or what we call a fat arrow and then we can pass in any parameters and then in the print curly braces here we can just same thing just return a plus b if I save that we get 3. so this is the just the regular Arrow function syntax now there are some things we can do to make this even shorter since we only have a single expression single just one line expression here that we’re returning something we can shorten this by getting rid of the return statement and the curly braces so instead of using add though I’m going to do subtract just so I don’t have to comment that 102 but we’ll say can’t subtract and it takes in A and B we have our Arrow now instead of putting my parentheses here I’m just going to directly say a minus B so this is saying I want to return this expression to the right of the arrow so this is the same as this of course except it’s it’s subtracting so I’ll go ahead and copy this down and let’s do we’ll say 10 5 and we’re going to call subtract and of course we get 5. so this is in PL it’s an implicit return because we’re not specifying the return keyword it’s just doing it so let’s say implicit return now there’s another way that we can shorten things up if your function only has a single parameter so let’s say we have a function called double and it takes in a single parameter and then what we want to return is whatever we pass in and then just multiply it by two so let me just run that down here real quick so if we do double him pass in 10 we get 20. now the way we can make this shorter just a little shorter but it’s important to know this is when we have a single parameter like this we don’t need to have parentheses around it okay now the way that I have my text editor set up and prettier and auto format if I save it puts it in automatically but what I can do is copy this I’m going to copy it and then comment it out and then over here in my console I’ll paste it in and you’ll see that that works so if I do double let’s say double um one we get two now if I try to Define this and leave off my parentheses but I have more than one param that’s not going to work okay so you can only emit the uh the parentheses when you have a single param so let’s uncomment these and just put a comment here and you can say can leave off parentheses with a single param now another thing that can cause a little bit of confusing of confusion is if you are returning an object so let’s say returning an object and this is due to the formatting of the you know having the arrow point to curly braces when you want to return an object with which also use Curl uses curly braces so to give you an example let’s say const we’ll call this function just create object and it doesn’t have to take anything in but let’s say I want this to return an object that has a name I’ll just do that and then if I save you’ll see that prettier automatically thinks to put a semicolon here which obviously isn’t what I want if I’m trying to make this an object so if I come down here and I do a console log of create object I’m going to get undefined so all you need to do is if you want to return an object this way you just surround the curly braces with parentheses and then of course we don’t want that semicolon so now if I save you can see we’re returning an object that has the name of Brad now I know we haven’t gone over high order array methods or callbacks or anything but that’s another great place to use Arrow functions so I’m just going to show you an example so let’s say we have an array which we’ll just call it numbers and let’s do one through five and on arrays there’s a method called for each and we haven’t gone over this yet but we’ll be getting deep into these types of methods later on but just to show you if we do numbers dot for each what you pass in here is a function okay and you could do it like this you could just pass in a regular Anonymous function and just pass in whatever you want to use for each number I’ll just use a variable called n and then I’ll just do a console log of n if I save that you’ll see it basically what this does is it Loops through and it just outputs logs each number okay I could do whatever I want with this number but I’m just choosing to log it out now this is a good place to use an arrow function because you can really shorten it up and make it neater so let’s say four each and instead of passing in the word function I can just put in my parentheses pass in actually in this case I wouldn’t even need parentheses since I’m using a single a single parameter but it’ll add it automatically in my case and then we have an arrow and since I just want to do a single console log I don’t even have to use curly braces I can just say I want to do a console log and Save like I said the parentheses get added but you really don’t need them and you can see it does the same thing so I think that this is you know more neater and short and concise than this but again it’s it’s all preference just like most things so this is let’s say Arrow function in a callback so callback is basically when we pass the function into another function and we’ll we’ll get into that later all right so hopefully this just gives you a basic understanding of how to format Arrow functions we’ll be using them throughout the course now in the next video I want to get into something called immediately invoked functions all right so when we deal with functions we usually Define them or declare them and then we invoke them when we need to run them however there is a way in JavaScript that lets us create a function or declare a function and invoke it at the same time and that’s using something called an immediately invoked function expression or an iffy for short iifi I’m sorry iife and there’s a few reasons why you might may want to do that one of the biggest is to avoid Global scope pollution so let me show you what I mean if we have in our folder here you can see I have a folder called iffy if I create another Javascript file I’m just going to call it other script dot JS and this could be like another library that we’re using or whatever it might be and let’s say in this script we have a global variable called user and I set that to Brad and I’ll just do a console log of the user and of course it’s not going to show yet because I haven’t linked it up to my HTML file so let’s go ahead and add that and we can say that this is coming from some other library that we didn’t even write so that another developer created so we’ll say another script.js if I include that now we’re seeing that that Brad value which is in this user variable now let’s say in our script well we want to have a variable called user as well so I’m going to set const user to John and as soon as I do that and save and it runs I’m going to get this user has already been declared okay because it was declared in the global scope of the other file and now I’m trying to declare it in this scope as well and there’s a few ways to handle this but one of the ways we could handle this is with an iffy so let’s go underneath here and I’m going to open up a set of parentheses the Syntax for an iffy is a little strange what we do is create an unnamed function in those parentheses and then whatever we want to happen so I’m going to actually bring bring this down into the iffy and then just do a console log of user now after the the first set of parentheses we need to open up another set to invoke it right because that’s a function we need this set of parentheses to invoke that so I’m going to go ahead and save this and you’ll see now we get we don’t get an error we’re able to have both of these variables of user because this this one here is not in the global scope okay it’s in the scope of the iffy and I could even create a function within here like let’s say we have a function called hello we’ll use Arrow function and we’ll just do let’s say console.log and we’ll say hello from the iffy now if I try to go outside here and execute hello I’m going to get an error that says hello is not defined because again it’s it’s scoped inside of this iffy so I would have to run it inside here like that now you can add parameters if you want so let’s say I’ll just create another one down here so it’s remember it’s 2 it’s parentheses side by side the first one has the function inside of it so I could pass in let’s say name and then let’s say I want to just do a console log of a string hello and then I want to concatenate onto that the name now where I pass that in is going to be right here so I’m going to pass in a string of let’s say Sean save that and we get hello Sean so that’s adding parameters to your to your iffy now you can have a named iffy because notice these are just Anonymous functions they don’t have any any name associated so if I wanted to I could say function and then give it a name like hello which I can do because the other hello is on a different scope and then whatever console log hello but you don’t really see this very much because you can’t call that function outside of of the iffy outside of that scope you can call it within it and that’s something called a recursion when you when you call a function from itself that’s recursion and it’s kind of an advanced topic which we’ll get into later much later and I wouldn’t recommend doing it if you run this you’re going to crash your browser because what’s going to happen is it’s going to run hello it’s going to console log hello then it’s going to call it again it’s going to console log again call it again and it’s just going to keep going until your browser crashes is going to cause what’s called what we call an infinite Loop so I wouldn’t recommend doing that but I wanted to show you you can create a named function I guess the other reason you might do it is for debugging reasons all right so that’s it for iffys we’ll we’ll probably get into these a little later in some projects but in the next video I want to give you a couple fairly easy function challenges all right guys so we have a couple challenges to do so there’s three of them here and basically I’ll just do one by one and you can pause the video after I explain each one and try it on your own so challenge one is to create a function called get Celsius that takes a temperature in fahrenheit as an argument and then Returns the temperature in Celsius for bonus points write it as a one line Arrow function so we’ll write it as a regular function first and then we’ll see if we can convert it and the expected result you just pass in a Fahrenheit like 32 and you get back the Celsius which would be zero and you can make the output look prettier by putting it into a string you can even add the the slash X B zero which is this this little degree symbol and you know put it in a template string like that and then hence the formula for Fahrenheit to Celsius is this right here so basically this Fahrenheit minus 32 times 5 divided by 9. you can read more about the formula here if you want so that kind of explains that all right and then what I’ll do is open up let’s search for a Fahrenheit I don’t even know how to spell Fahrenheit Fahrenheit to Celsius converter online okay so here we have an invert and this just shows you the formula right here so basically we just need to um I’ll put this in our JavaScript where the Fahrenheit temperature is the argument so if you want to pause the video and do that now go right ahead so I’m gonna just put in a comment here say challenge one and let’s create it as a regular function first so we’ll say get Celsius and then that’s going to take in a Fahrenheit temperature and then basically what we’re going to do let’s just do Celsius and let’s set that to the formula which we can probably yeah we’ll just grab it right from here definitely need to know that stuff like this I usually find on like stack Overflow or using the the GitHub copilot extension is really helpful because it’ll get you stuff like that so I’m just going to paste that in and then what we can do is replace that capital F with our lowercase f because that’s the argument that’s being passed in right and then let’s return Celsius cell CS right and then let’s do a console log here of get Celsius and let’s pass in 32. so if we look at down here we get zero so let’s try something else if we pass in 40 we get four point and then a bunch of fours so if I put in 40 here we get same thing we put in 50 we get 10 let’s put 50 in our function and we get 10. good now we can turn this into a one line Arrow function if you want to pause the video and do that you can go ahead but I’m going to just I’ll comment it out in a second but let’s do const get Celsius we’re going to set it to an arrow function that takes in Fahrenheit and then we know that basically we just want to return this right here right we didn’t have to put this in a variable name we could return it directly but down here we can use an implicit return so I’m just going to paste that in all right and then we’ll go ahead and comment this one out and let’s try it again I save we get 10 if I pass in 32 we get 0. all right so this is a nice clean function so I think that that’ll do it and we could put it inside of uh a template string with this little symbol so for example instead of just logging the answer we could say we could put in back ticks and say the temp for what do we do here yeah we’ll just say we’ll just say the temp attempt is and then put in our get Celsius with 32 and then outside of that the curly braces I can paste that in and then we’ll put an uppercase C actually let’s not have a space there so now it says the temp is zero degrees celsius if I pass in 50 and say we get the temp is 10 degrees Celsius so that’s the first challenge so the next one I I don’t even really remember what these are I did these quite a while ago so create an arrow function called min max that takes in an array of numbers and returns an object with the minimum and the maximum numbers in the array so we want to be able to pass in an array of numbers and then what we get back in return is a an object with the minimum and the maximum of you know of the numbers in that array so as far as hints you can use the math dot Min and math.max methods to get the Min and Max you can also use the spread operator to spread the values of an array into separate arguments okay so yeah let’s try that and if you want to pause the video and do it that’s fine as well um I’m just gonna put a comment in here challenge two and let’s create our function called min max and then that’s going to take in in Array so I’ll just call this ARR and then remember we can use the math object Min and Max methods so let’s say const min and we’ll set that to math.min and then I want to take basically this this doesn’t take in an array it takes in just a bunch of numbers like this one two three and so on so if we want to take just the values in the array remember we can use the spread operator and then we’ll go ahead and add our array and just to kind of test that out let’s do a console log of uh Min and then we should we can just call this because we we logged from the function erased oh we didn’t we need to pass in an array so let’s just do one through five and save and we get one which is the the minimum so now we can copy this down and let’s get the max So Max and then I’m just going to console log Max and we get five if I add to this 6 then I get 6. so we know we’re we’re halfway there we have that now we just need to create an object so let’s go down here and let’s return an object with Min now remember when if if your variable name is the same as your your key here you don’t need to have the variable name you can just do that and then same with Max all right so that should do it now we’re returning so we do need to wrap this in a console log if we want to print it out and we’ll save so we get min 1 Max 6. if I add let’s say 31 in here and I save we get min 1 Max 31 if I get rid of the one Min will now be 2 max 31. okay so that should pass the challenge now for our Challenge three it says create an iffy we talked about those in the last last video that takes in the length and width of a rectangle outputs it to the console in a message as soon as the page loads so we know that if we write it in iffy it runs right away when the page loads so on page load we should see this message an area of a rectangle with a length of 10 and a width of 5 is 50. okay so the hints the area of a rectangle is the length times the width okay so it takes in the length and the width that means we just need to multiply it and this should get passed into the ifeas arguments you do not have to return anything from this function just log to the console so that’s actually pretty easy um so it really just tests your skills to create an Effie so let’s come down here and you can pause the video right now if you want to so let’s say challenge three and we’re gonna create an iffy so remember we have a set of parentheses and in that is where we create our function now I don’t think I showed you in the last video that we can actually use an arrow function here like I could do just a regular function like this but you can also just do this so that’s what I’m going to do and it said to take in a length length and width and then inside the function body let’s get the area so we’ll say const area and then we can get that with length multiplied by the width and then let’s just do a variable for the output we want to log so that’ll be a template literal and we’re going to say the area let me just check this out again I’m actually going to just copy this so if we paste that in and we just need to replace these values so we know we have the length and the width passed in so we can replace this 10 right here with the length we can replace this 5 with the width and we can replace 50 with the area and then of course we need to add in our parentheses and then when we pass in the the arguments that goes in here so let’s say 10 and 5. and of course we need to Output this so let’s just do a console log and well we’re going to Output output so the area of a rectangle with a length of 10 and a width of 5 is 50. so if I were to change this now let’s say 20 and 10 save that length of 20 and a width of 10 is 200. all right guys so I hope that the the challenges I hope the description is good enough for you to kind of understand what I’m asking you to do I’m not the best at at doing challenges or creating them honestly so hopefully that’s sufficient all right so what I want to start to talk about next is the execution context which is more behind the scenes stuff and and how how things work behind the scenes which is a little Advanced especially for this stage in the course but I said it a million times already I want to give you a full picture of what’s what’s going on as we’re writing our code all right guys so now we’re going to talk about execution contacts which might sound a little intimidating especially if you’re a true beginner but just know that learning this stuff now and learning the the bigger picture of what’s happening when your code is running is going to benefit you more than if you learn this stuff two three years down the road like I did so execution context just think of this as something that’s going to happen behind the scenes we’re not looking at any new Advanced code or anything like that in fact the example code we’re going to use is just very simple stuff we’ve already done just creating a variable creating function running a function all right now as far as what this is the execution context is a special environment that’s created by the JavaScript engine in the browser or if you’re using node.js the the engine that node.js uses which is the V8 engine and this special environment this execution context includes the currently running code and everything that aids in its exit execution and when it’s first created that’s called the the global execution context okay you can think of it as like the global scope and then anytime you invoke a function that function will have its own execution context that’ll last for the span of the function okay when the function is done then that function execution context is done now to kind of visualize the execution context I created this box so you can think of it as a box with two sides where you have your variable What’s called the variable environment on one side and this is going to be all the variables and all the functions in your code stored in key value pairs in memory all right so that’s the memory and then we have the execution side which is the thread of execution so JavaScript is what we call a single threaded language a thread you can think of as like a process and your code is executed line by line on that thread or on that process all right so just to be clear JavaScript is single threaded and it’s synchronous so it’s executed line by line there are asynchronous capabilities which we’ll talk about later different web apis and stuff like that but just know that at its core JavaScript is single threaded and it is synchronous now there’s two phases when the execution context is created so the first phase the memory creation phase you can think of as like one swoop through before your code is actually run okay so the memory creation phase does not actually execute your code it does a couple things so the first thing it does is it creates the global object in the whether that’s in the browser or in node.js in the browser the global object is called window in fact if I go to Chrome real quick and I go into the console and I type in window and I hit enter it’s going to show me that window object and all the methods and properties on it and there’s a ton of them okay different apis and stuff and we’re going to get into a lot of this later on now and that’s created by the execution context in the memory phase now the second thing it does is it creates the this object and binds it to the global object that’s why if I come in the console and I type in this and I hit enter it’s going to show me the same exact thing the window object because that’s it binds it to that all right then what it does is it sets up the memory Heap for storing your variables and function references so remember this box right here all your variables and functions are going to get put into here during the memory creation phase and then the last thing it’s going to do is it’s going to set the value to all of those to undefined okay so if we look here these these values here these are all going to get set to undefined in the memory creation phase they don’t get filled with values until the code is actually executed okay which is the second phase the execution phase where it goes through line by line and if it hits a function a function invocation then it will create a new execution context for that function now to give you a better picture we’re going to go through we’re going to step through each line of this code and I’m going to show you exactly what’s happening within the execution context and like I said this code is very simple we’re just creating a couple variables we’re creating a function that returns a sum of two numbers and then we’re just creating some variables that will contain the return value of this get sum function so a couple things to keep in mind there’s two phases we’re going to go through the memory creation phase and the execution phase and whenever we invoke a function like this it creates a kind of a side function execution context so let’s get started so we go ahead and run them the memory creation phase or we don’t run and it just gets run and on line one it’s going to set the x variable in memory it’s going to allocate it and store it as undefined okay remember I said variables in the memory creation phase are they’re put into memory but they’re stored as undefined it’s going to do the same online 2 with the Y variable store that to undefine now line three it hits a function and functions are allocated to memory but they’re not stored as undefined I think I might have said that the the all the code within the function gets stored to memory okay it doesn’t get executed it just gets put in memory for now and then it’s going to skip to line seven where someone is going to get allocated to memory stored as undefined okay we’re not remember we’re not executing anything yet so the functions don’t get executed we’re simply putting the the variables into memory same thing with sum2 that’s put into memory stored as undefined now what’s going to happen is it’s going to go through the execution phase so it’s going to go back to line one and in line one it’s going to take 100 and put that into the X variable in memory remember X is already in memory as undefined from the creation phase but now that we’re executing it’s going to put 100 in for X okay next line 2 is going to place the value of 50 into the Y variable then it’s going to go to line three but it’s going to skip this function because there’s nothing to execute this is just a function a function definition then we go to line seven it’s going to now invoke get some because remember we’re in the execution phase so this is a function it’s going to get run and it’s going to create a new function execution context all right now remember when we when a new execution context is created it has two phases once again so now we’re going to be in the memory creation phase 4 the get sum function execution contacts so you can think of it as like a nested execution context so on line three what it’s going to do in the memory creation phase is it’s going to assign N1 and N2 to memory and store it as undefined okay remember we’re in the creation phase for the function execution context so it’s going to take these two and store them in memory as undefined then it’s going to go to line four it’s going to store sum as undefined it’s going to go to the execution phase now of the function so N1 and N2 are going to get a signed 150 and the reason for that is because we’re passing in here X and Y which are set to 150. okay and then on line four the calculation is done and 150 is put into this sum variable in memory then line five is going to return and tells the function execution context to return to the global execution context with the sum or the value of 150 okay and that’s going to get stored in here the return sum value is put into the sum 1 variable then it goes on to line eight it’s going to do the whole thing over again it’s going to open up another execution context for the function and do the same thing just with different parameters this time 10 and 5. all right so just to quickly recap because I really want you guys to get this we run this block of code it starts the the global execution context in the memory creation phase it goes through each line and it’s going to set all the variables to undefined in memory it’s going to set the function code into memory okay once it does that it starts the execution phase where 100 is put into x 50 into y it’s going to skip the function declaration because we’re in the execution context there’s nothing to execute once we 7 it sees there’s a function that opens up another execution context for the function okay and then it goes through the memory phase for the function then the execution phase for the function and then moves to line eight and it’ll have to do the same thing because we hit another function all right so this doesn’t really affect how you write your code right now but it will benefit you in the future just knowing how this works behind the scenes now in the next video I’m going to run this block of code and I’m going to use the the browser debugger to kind of put breaks in so we can see exactly what’s happening or as much as we can see within the browser so in the last video we talked about execution context and we stepped through a block of code and I showed you what happened during the memory creation phase and the execution phase well here I’m going to do the same thing you can see I have the same exact code in in my vs code and we’re going to do the same thing from within the browser and we can do that by using the sources tab in the dev tools and over here you’ll see our files and if I click on script.js we’re going to see this the same code right here now using the debugger I can put what we call a break point anywhere I want and that’s going to stop the code from running at that point so what I’m going to do is put it right at the beginning so it’s actually not going to execute the script so I’m going to reload the page and none of this is executed but the memory creation phase has been run so down here you can see all these variables X Y sum 1 some to there they’ve all been put into memory and set to undefined because remember with with the memory creation phase it puts your variables in memory and sets them to undefined okay before the execution now remember functions get stored in memory and the entire code in the function gets stored however that’s going to be down here in global so that’s called get sum so if we look down here we should see a get some function right here all right so that code is stored in memory as well now one interesting thing is if you used VAR instead of const or let then those variables would be put on the the global scope as well and and that we can get into hoisting and stuff later on but what I want to show you now is if I step through this so I can use this little arrow icon to to execute the line the code line by line and you’re going to see what happens over here so I’m going to click the arrow it’s going to run the first line const x equals 100 and now we’ve started the execution phase okay normally it just goes through and does it you know all together but uh or it does it real fast it doesn’t pause like this but now we’re pausing line by line and you can see that 100 has been put into X okay because we’ve started at the execution now I’m going to click this Arrow again and execute the second line and you’ll see that 50 has been put into y now it skips the function definition because there’s nothing to execute and goes right to this get sum where it where it’s being invoked now remember when we invoke a function it creates a new function execution context I’m going to click the arrow and now you’ll see this new area called local which is our function execution context and the first line has been has has Ran So N1 and N2 contain 150 because our first function call we passed in X and Y which are 150. now if I click this again and run this line right here it’s going to put 150 into sum so I’ll click it again and now you’ll see sum has 150 in it now if we step out of the function it’s going to go to the next get sum which is being passed in 10 and 5. so it’s going to open up a new execution context with 10 and 5 as the arguments here is the variables if I clicking again it’s going to add the sum click it again it’s going to go to the next line to the console log and now our script has been run all right so that’s what it looks like when you go through line by line but you saw even before we executed anything the creation phase ran and put our variables and our function into memory but if this is confusing to you don’t worry about it my my point of doing this is just to show you what’s going on under the hood and how this is actually run within the browser so in the next video we’re going to talk a little bit about something called the call stack and then after that we’ll get back to syntax creating conditionals and loops and so on okay so while we’re on topics that are kind of behind the scenes things that happen when we run our code we talked about the execution context I want to also talk about the call stack this is something that will be important later on when you get into more advanced JavaScript but I just want you to understand the basics of it so when we run a function we know that it opens up a new function execution context it also gets added to something called the call stack now a stack is a data structure in not just JavaScript but in in many programming languages and it operates in a very specific way it’s it’s last in first out or l-i-f-o meaning that the last thing to come on is the first thing to come off and the better the next slide will give you a better visualization of that but the call stack is you can think of it as a manager for your functions or a manager for your your execution contacts and at the bottom of the stack you have your Global execution contacts and then when a function is invoked that gets put on the call stack when it’s done it gets it gets popped off all right so if we look at this very basic piece of code here we’re running three functions or creating three functions for our second third and then running them okay and we’re doing this all in the global scope they’re all being run in the global scope so what happens here is the first function is invoked it gets pushed onto the the stack that’s the terminology just like with arrays push and pop so it gets pushed on first ends and then gets popped off then second runs gets pushed on popped off then third runs gets pushed on popped off so that’s how this piece of code would work with the call stack now this piece of code is a little different so we again we have first second third but we’re just running first in the in the global scope and then in first we’re running second and then in second we’re running third so what happens is we run first it gets pushed on while first is running second is run so that gets put put on top of first because first is still running it’s still open and then in second third gets called so second is still running so third gets pushed on when third ends third gets pushed off I’m sorry popped off and then second end gets popped off first popped off so it’s just it’s the same thing it’s last and first out so what I want to do now is show you that those same two pieces of code in the browser and show you the call stack in the sources tab so as you can see I have the first example I showed you here I have the second one commented out for now and I’m going to go to the sources tab and go to script.js and what I’m going to do is put my my break point right at the first function where it’s called and then I’m going to reload the page and right now it hasn’t run anything I’m going to once I click this Arrow it’ll run this line the first function and if you look down here there’s actually a tab called call stack and you can see right now first is on top of is is is first on top of the global execution context that’s what this Anonymous is all right so first gets put on the stack and then let’s step through it step through it again finish it up now we’re going to run second gets put pushed on the stack step through it it gets popped off let’s run third that gets pushed on WE step through it and then it gets popped off all right so that’s how this piece of code works just like I showed you in the slide now I’m going to just comment this out and the second example I’m going to uncomment that so remember this is where we’re actually running second in first and third and second so I just want to show you how this would work so we’ll come down here actually let’s uh let’s just reload this whole thing real quick and then I’m going to put my break point right here at first and then reload and then if we run the function you’ll see that first is put on the stack now it’s going to go to Second which is still in first okay and we’ll run that and now look second is on top of first inside second we run third so let’s do that and now third is on top of second so this looks exactly like the diagram that I just showed you all right and then if we step through third will end gets popped off now you can see second is on top we’ll run that that gets popped off first that gets popped off so I just wanted you to understand at the very at a very basic level how the call stack works so in the next section we’re going to start to look at control flow and logic and conditionals hey guys welcome to section four so I know that some of you might be getting a little antsy because you want to get into the the document object model stuff and creating things in the browser and events and all that and that’s coming soon I promise but this stuff is very very important these are the fundamentals these are things that you absolutely have to know to do anything in JavaScript so in this section we’re going to look at logic and control flow which is something that is very important not just in JavaScript but in any programming language because you need the ability to make decisions you need the ability to run certain blocks of code if something is is true or false so we’ll be looking of course at if statements or if else statements we’ll be looking at switches I want to get more into the truthy and falsy values I know we touched on that a few sections back but I really want to dive into that logical operators logical assignments shorthand if statements and the ternary operator so that’s the the type of of stuff I want to get to here we’re going to have a couple challenges as well alright so let’s get into it all right so one of the main ways to have control of the flow of your application is with if statements and if statements are in just about every programming language if they’re not then there’s there’s most likely something similar so the format of an if statement is very simple we just say if and then in here we can put either a value or an expression so I’m just going to put true in this one and then if that passes so if it’s true then whatever I put in here will run I’m just going to say this is true if I save that you’ll see that that runs now if I were to copy this down and change this to say false and then we’ll say this is not true if I save that that’s not this block of code right here line six is not going to run because this expression that I passed in is false all right now we can also evaluate expressions that with uh with operators like equals or less than so I actually have a chart right here so we can test if something is equal to with both double and triple equal signs or not equal to greater than less than and also greater than an e or equal to or less than or equal to so just to give you a quick example and let’s actually create a couple variables here we’ll say x equals 10 and let’s do y equals 5 and we’ll say if x is greater than y then let’s just do a console log put through some backticks in here and we could say x is greater than y save that and we get 10 is greater than 5. if I want to use an equal sign or our triple equals whatever not quadruple equals that’s not a thing and then here we’ll say x is equal to Y if I save that this block of code isn’t going to run because this is false right if I change y to 10 and I save then that will run now this one’s not going to run because 10 is not greater than 10. if I were to use greater than or equals that will run okay so we could say is greater than or equal to save that we get 10 is greater than or equal to 10. now as far as if else goes if I change y back to 5 this right here this block of code is not going to run but we might want something to happen if this is false so if this is true this line will run then we can add an else if we want and say let me just just copy this and I’ll say is not equal 2y so if I save that now we’re going to get 10 is not equal to 5. so the else is going to run because this expression is false now we talked a little bit about we talked quite a bit about scope in in the last section but I just wanted to remind you that blocks like if statements have their own scope so if I put it doesn’t really matter what I put in here I’ll just say if X is not equal to y and then I just want to show you in here if I were to create a variable like let’s do Z and set that to 20 and let’s say console log and let’s see X I’ll just say I don’t know we’ll just say Z is 20. it doesn’t really matter what I want to show you here if I save that we get 20 is 20. but if I were to try to access that Z variable I can’t do that Z is not defined and that’s because I use const if I use let here to Define Z I get the same thing if I use VAR it actually works because VAR is not Block Level scoped it’s function scoped like it you can’t use if I were to say VAR Z in a function I can’t use it outside of that in the global scope but with other blocks like loops and if statements it’s not scoped okay so and that’s it’s not a good thing that this is not scoped because then someone might want to access that Z variable somewhere else and they’ll be able to so that’s why Latin cons to are actually created was to keep Block Level scoping now the next thing I want to show you is some shorthands that we could use I don’t really do this and and recommend it but it is possible so let’s take this right here this if statement and let’s just say shorthand if so paste that in and I’m not talking about the ternary operator we’ll get to that later but I can actually get rid of the curly braces here so that is perfectly valid JavaScript if I save that we get 10 is greater than or equal to 5. all right and then if I wanted to use an else I could after the semicolon do else and without parentheses I’m sorry without curly braces we’ll say I don’t know it doesn’t matter we’ll say this is false and save that and if I change let’s say y to 50 and save that you can see this is false now this this looks cluttered to me I don’t like it I I would use parentheses but everyone has their own preference but I just want to show you that if you have multiple lines like right here we just had a console log if this was true you can do this with multiple Lines by using a comma so let’s say I also want to log let’s say console.log this this is true and if I save that you’ll see I’m not getting any errors if I change this back y back to 5 and I save it’s going to run both this line right here and this line right here this is this it’s true this is true so you can do this but I really don’t like the syntax and wouldn’t suggest it all right so that’s it for just the basics of of um if statements in the next video I want to get into else if as well as nesting okay in the last video we looked at if statements and if else where we said if something is true do something else do something else now you might have situations where you have multiple conditions that you want to test and do and run some block of code based on these multiple conditions and that’s where else if comes in so let’s make this a little bit more interesting we’ll create a date so we’ve already looked at the date object and I’m going to set it to a specific date let’s do 10 uh we’ll do 10 30 22 and then I want to put the time so eight we’ll do eight o’clock so eight zero and zero and remember you can pass a string in here if you want doesn’t have to be these um these arguments and then I want to get the hour because that’s what I want to test so I’ll say const hour and then on the date object we’ll run the get hours method and if we console log that so console log our then we’re going to get eight right because I set it to eight if you if you don’t pass anything in here it’s going to give you your current hour so mine would be 10. but we’re going to keep it at eight so we’re all on the same page and then let’s do an if statement here so we’re going to say if the hour is less than 12. all right so if the hour is less than 12 then let’s do a console log of good morning all right because it’s less than 12. now I could do else here so if I do else we could do console log and let’s say good night and if I run this I’m going to see good morning because it’s 8 right now what if I want to say good afternoon if it’s at a certain time in that case I would do an else if so I’m going to go where this else is where this uh this first ending curly braces and just put that on the next line and then say else space f and then open up a set of curly braces and we could put this here and let’s say if the if the um what is it our is less than 18 then let’s say console log and we’ll say good afternoon all right so basically if it’s less than 6 p.m it says good afternoon now we’re getting good morning even though it is less than 18 right we’re at eight but this ran first so it’s going to first look at this if the hour is less than 12 which ours is then this is going to run and it’s not going to do anything further if the if the time is let’s say 13 and I save now we’re going to see good afternoon because this doesn’t pass the first one right so it’s going to say else if the hour is less than 18 which it is it’s 13 so now that’s going to run if I change that so that this is also false so if this is false and this is false if like if we say 19 then the else the final else is going to run okay so that is the else if now we can also nest if statements let’s say nested if so I’m going to say if let’s say our is less than 12 and actually you know what we’ll just let’s just copy this because I’m doing kind of the same thing here but I want to show you how we can Nest this to get even more options so let’s say if the hour is equal to six if it’s 6 a.m then we want to console log wake up so we know that in here it’s going to be this this code is going to run if the hour is less than 12. obviously 6 is less than 12. so what I’ll do is in here I’ll Nest another if statement and we’ll say if the hour is equal to 6. then let’s console log let’s say wake up okay so that’s how we can nest and maybe maybe at night time let’s go down here and let’s Nest another if statement okay and we’ll say if the hour if the hour is greater than or equal to 20 then we should be sleeping so say console log and we’ll just put uh a bunch of Z’s in here all right so let’s save that and we’re still going to see good night because we’re at 19 right now if I were to put the hour to six and save then we’re going to see wake up if I put the hour to uh and we’re going to see good morning if I put the hour to let’s say 21 we should be asleep so now we see good night and we see the Z’s so that’s nested if and you can Nest as many levels as you want you could go in here and put another if statement but that’s when you when you get to that level you might want to think about something like a switch which I’ll talk about in the next video now another thing we can do is have multiple conditions in a single if statement so for instance let’s say if the hour we’ll say if the hour is greater than or equal to 7 but let’s say I will also want to test if it’s less than 15. in that case I could put a double Ampersand and that’s going to be the and operator so I could say and if the hour is less than 15. so let’s say that’s the work day so I’ll just do console log and say it it is work time all right so if I save that I don’t see it because right now the hour is at 21 but let’s set it to we’ll say 9 A.M and we’re going to see it is work time now this is just one operator the and we could also do or so maybe we want to say if the hour is let’s say equal to 6 or which is going to be the double pipe characters or the hour is equal to 20. then let’s say that’s the time we brush our teeth so we’ll say brush your teeth save that now if we put the hour at either 6 or 20 so at 6 we’re going to see wake up and brush your teeth okay the wake up is coming from right here and the brush your teeth is coming from here because the hour is 6 or 20. okay so that’s or and then this one is if the hour is greater than or equal to 7 and the hour is less than 15. all right so in the next video I’m going to show you another way that we can evaluate expressions and do certain things depending on the result with something called a switch all right so now we’re going to get into switches which is another way to evaluate expressions and values so let’s go ahead and create a new date just like we did in the last video so I’ll say new date and let’s just do 2022 yeah we’ll just do uh arguments so 2022 one so that’s the month and then whatever 10 and we’ll do eight zero zero so it’s eight o’clock and then I’m gonna get the month so let’s say const month equals get month D I’m sorry D dot get month and then let’s check that out so month and save and we get one so we’re in January all right now I’m gonna create a switch that takes in month and evaluates it so basically we we look at month and we can create different cases for the value so for instance the case of it being one so this is the syntax case then the value and then a colon and then this is the block of code we would run so I’m just going to do console log and we’ll say it is January and then once we’re done in this case we want to write a break statement so we just say break which is kind of like a return it just breaks out of this case and then we’ll do case two colon and do a console log here and say it is February and break and we’ll do one more case three and console log and say it is oops it is March okay now if it doesn’t match any of these what you want to do is have a default so whatever you put in this default will happen if it doesn’t match any one of those so I’ll say it is not January February or March and we don’t need to put a break on the default so I’m going to save this and you see we get it is January now if I come up here and I change the month to two it says this is February if I change it to three it is March and if I change it to four or anything else it’s going to say it is not January February or March all right but I’m just going to put it back to January so I mean switches are most commonly used with immediate values meaning it’s we’re checking the month directly you can use it with ranges though like we did with the hours in the last video so for example we could do switch and then what we would do in here is pass in true and then we could say case and say our actually we didn’t Define our yet didn’t did we so let’s go up here and let’s just do what we did in the last video we’ll say hour equals D dot get hours and then we’ll come back down here and let’s say case hour is less than 12. and then we’ll console log here good morning and then break and then we’ll do another case and this one will be our is less than 18. and we’ll console log good afternoon and then break and finally we’ll do case hour actually we’ll just do the default and for the default we’ll do good night because obviously it’s not going to match anything else so if I save that we see good morning if I change the time because right now it’s the time is eight if I change it to uh let’s see 13 and save we’re going to get good afternoon and if I change it to anything above 18 like 19 it’s going to say good night so we can do it like this as far as ranges so those are switch statements you don’t see them they’re not as common as if statements but if you have something where you have like you know five six seven plus else if I think a switch is uh that’s a good use case for a switch all right you see them in like reducer functions and stuff like that when it comes to like front-end Frameworks and State Management and all that so those are switches in the next video we’re going to do a little challenge all right guys so now that you know how to deal with functions and conditionals we’re going to do a little challenge so let me just open this up here so the calculator challenge basically what I want you to do is create a function called calculator that takes in three parameters num1 num2 and then an operator and the operator can be plus minus multiplication or Division and the function should return the result of the calculation so if anything other than the four operators are passed in then the function should return an error message like invalid operator so as an example if we pass in 5 2 and plus we should get 7 5 2 minus three five two asterisk 10 and 5 2 2.5 and then if we pass in anything else that’s not one of these four operators you should get an error message you can return it or console log it or both as a hint you can use an if statement for the operator but this is also a good example for using a switch statement so it’s really up to you or you could do both so go ahead and pause the video try it out and then come back so what I’m going to do is use a switch so let’s create our function first it takes in num1 num1 num2 and operator and then I’m going to just create a variable called result and then we’ll run a switch on the operator and for the first case we’re going to look at see if a plus sign is passed in and this should have quotes around it because it’s a string if that’s the case literally then we’re going to set the results to num1 plus num2 and then we’re going to break all right and then what I’ll do is copy this down we want four of these because we have four operators to test so this one will be minus minus and then this one will be multiplication make sure that you change both here and here all right and then what I’ll do is for the default we’ll set the result because obviously it’s not going to be any of those operators so I’ll say invalid operator and then outside of the switch I’m going to first console log the result and I’m also going to just return the result all right and that should do it so now to test it out we’ll come down here and let’s do calculator and let’s pass in we’ll just use the example five two so we’ll say five two and then we’re going to pass in plus as a string we’ll save that we get seven if we do a minus sign we get three if we do an asterisk we get 10 and if we do a slash we get 2.5 and if I do anything else like an ampersand then we get invalid operator all right so that is the result that we’re looking for now if you used an if statement if you used elseif or whatever that’s absolutely fine as long as you get the same result so in this video we’re going to look at truthy and falsy values this is something for you to it’s really important for you to understand so try and remember these at least the falsy values because anything that is not falsy is going to be truthy and what I mean by that is if you have something you pass into an if statement that’s not something equal to or is something greater than maybe you had just have a string like an email so we’ll say test at test.com and then I pass that in here so I want to evaluate email and then I’ll just console log here you passed in in an email and if I save that you’ll see that that runs so this was evaluated to true or I should say coerce to true if you remember we talked about about type coercion where JavaScript implicitly changes the type so when you pass something into an if statement it’s always going to be coerced into a Boolean okay and we can even do a console log here and say Boolean and pass in email and you’ll see we get true the reason for this is that a string with anything in it is a truthy value okay so it’s always going to result to true so what I want to do is paste in that will do the falsy values first so let’s uh we can just just get rid of this and I’m going to paste these in so there’s six falsy values and what I’m going to do is set a variable let’s say const x and I’m going to set it to the first one which is false and I’m going to do two things I’m going to pass it into Boolean to see what it evaluates to and then I’m gonna I’m sorry that should be X and then I’m going to do an if statement so I’ll say if x and then we’ll say uh console log this is we’ll say this is truthy if this is true right and then let’s say else then we’ll console log this is falsy if I save that we’re going to get this is falsy and false because obviously false which is already a Boolean is going to be a Boolean false now zero if I pass in 0 to X we get the same result because if we pass zero into an if statement that’s a falsy value so we’re going to get false for that if we pass in an empty string that’s also a falsy value that’s why a lot of times like with web forms when you’re doing validation you’ll check to see if the value is there or not so in in it’s passed in as an empty string if it’s submitted as an empty web form or an empty input all right so an empty string null is also going to be falsy undefined is going to be falsy and then Nan are not a number is also going to be falsy now anything that is not falsy is going to be truthy so anything other than these six values right here but there are some things that are a little confusing that you might think are falsy and even even developers after like a year still forget that these are falsy some of these so I’m going to paste in some of these truthy values like I said everything else is not falsy but let’s try some of these so obviously true is going to be truthy right if we do zero but within a string of course that’s truthy anything in a string is truthy even a space if I put a space here that’s truthy but if it has nothing then that’s going to be falsy all right if I put false in a string that’s truthy because that’s not an actual Boolean it’s a string with something in it it doesn’t matter what it is as long as it’s something another thing that can be confusing is an empty array if I do that that’s truthy you might think if we say if and then an empty array you might think that that’s going to be falsy because there’s nothing in it but it’s still an array if you want to get the the length I’m sorry if you want to check to see if there’s something in an array then you want to check the length same thing goes with objects if we have just an empty object that’s also truthy if we have a function that has nothing in it that’s going to be truthy as well so this is really important for you to remember that it’s going to be true unless it’s one of these things right here now let’s talk about some caveats so I’m going to say truthy and falsi caveats I was going to do this in a separate video but we’re only at four minutes and something so let’s say let’s say we have a web form that’s asking how many children we have and I’ll create a variable to represent that so I’ll say Khan’s children equals two let’s say that’s what we passed in and then we want to validate the form so we’re saying if children then whoops then we’ll do something let’s just say a console log with backticks and we’ll say you have whatever number children and then else then we want to tell them to enter their children right the number of children so we’ll console log and say please enter number of children okay um and this is something you commonly see in web forms if a field is required so I’m going to save that we get you have two children right they passed in two pass in one you have one children now what do you think is going to happen if we have no children and we choose zero let’s say it’s a select field and we select zero well it says please enter number of children or I have no children so I’m selecting zero the reason it’s doing this is because zero is being evaluated here and zero is a falsy value so you can run into some issues with this I’ve actually seen this same issue over and over so a solution here one thing you could do is say is children not equal to undefined if I do that now it says you have zero children another thing I could do is run children through it uh not is Nan so is Nan is is not a number and what I’m saying here is is it not not a number if I save that that works as well you have zero children if I put in three that’s going to work as well so that’s another solution you could do um but yeah you just want to make sure you know what you whatever you’re passing in make sure you know what that coerces or what that evaluates to now another caveat that we see is checking for empty arrays so maybe you have an array of blog posts and if there are no posts you want to say like no post to show or something like that so let me just show you if we do const yeah we’ll just call this posts and we’ll set that to an array and we’ll say post one and post two right and then we’ll console uh sorry we want to do an if statement so if we say if posts then I’m just going to console log here list posts else then we’ll console log no pose if I save that it says list posts so I mean in real life you’d probably list your posts in the Dom which will you know we’re going to get to soon but if you have no posts and save it still says less post it doesn’t say no posts I will say no posts to list it doesn’t say that because an empty array is truthy right if we go up here an empty array is a truthy value so that’s going to evaluate to true so again know what you’re passing in so what you could do here remember we have a length property on arrays you can see that the length is zero if I add something in here then it’s one okay one two without whatever however many is in there so what you could do is say if post dot length is greater than zero now if I do that it says no post to list if I go in there and I add in post one and save now we get list posts so if you want to check for an empty array you want to do it like this now with objects let’s say check checking for empty objects so we’ll say const and I don’t know just say user equals and let’s set it to say name and Brad and then we want to check say if user then console log and we’ll just say list user else then we’ll console log no user all right so if I save that we’re going to get list user now if I if I empty the properties and it’s just an empty object It also says list user so you might want to check to see if there’s anything in the object and doing it like this is not going to work because this is a truthy value now we can’t use length directly on an object so if I if I were to try to console log user dot length you can see it gives me undefined so we can’t use length what you would do I mean there’s a few ways you could do this but one of the most common things to do is to use object dot keys and we looked at this in a past section if we say object dot keys and we pass in our user that will give us an array of the keys right so then since that’s an array then we can call length on it and we can say if that is greater than zero or you might want to say if it’s equal to zero then you would do this you know you might do it the opposite way around so let’s save that and now we get no user if there’s nothing in here if I add in a name and save now it says list user now another thing that can be confusing is using Lucy quality which is the double equal sign and this is one of the reasons that I I just about always use a triple equal sign so if we were to do a console log and say false double equals zero okay so we’re comparing false to zero and we’re getting true and the reason for that is because 0 is a falsy value and obviously so is false so if I were to do let’s say an empty string equals zero again I get true if I do no equal to undefined I get true so there’s many cases if you’re trying to compare these you’re not going to want true so that’s where the strict equality comes in if we add another equal sign to all of these oops then we’re going to get false for all of them because this will check the type as well okay um so again I always use triple equals but everyone has their own preference so those are some of the caveats that that you might run into when you’re dealing with true truthy and false values I don’t know if caveat’s the right word but some some areas of confusion so hopefully that clears that confusion up all right so in this video we’re going to get more familiar with the logical operators especially the double Ampersand and the double pipes which are the and and or logical operators so first thing I want to do is just do a console log here with a couple Expressions let’s say if 10 we’ll say if 10 is greater than 20 which we know is false double Ampersand which is and and let’s say 30 is greater than 15 which is true if I save this we’re going to get false because when we use the double Ampersand in this in this way all everything here has to be true okay because it’s this this expression and this expression and we can add more in here as well like we’ll say uh let’s say 40 is greater than 30 which is true if I save this is still going to be false I could add a million more true things it’s still going to be false because this first one is not true if I change that to 10 is less than 20 which is true which makes them all true then we get true for this whole thing now when it comes to the or operator let’s say if 10 is let’s say 10 is greater than 20 which is false and then I’ll use the double pipes which is the or and then 30 is greater than 15 which is true if I save that we get true even though the first one is false one of these is true which is what matters it’s one or the other so if I make both of these Falls like say 30 is less than 15 then we get false okay so with the double Ampersand they all have to be true with the or just one of them has to be true now you’re going to see these used in in other ways as well so I’m going to create a variable here and actually let me just put a comment because we’re going to look at doubling ever since and this will return so if we add a bunch of values and we use this operator this will return the first falsy value or the last value so let me show you what I mean if I do a console log a and then I’m going to set here a equals let’s say 20 uh 10 double Ampersand 20. if I save that I get 20. so if we read this again we’ll return the first falsely value or the last value we have two values here 10 and 20 none of them are falsy so it’s giving us the last if we do another double Ampersand and we do 30 that’s going to give us 30 because again no falsy values so it gives us the last if I change this 20 to a zero which is falsy then we’re going to get that zero all right if I copy this down and I do before that zero let’s say an empty string which is also falsely then I’m going to get that empty string so that’s how that works now you might be saying well this doesn’t look you know when would I do this when would I use this so to give you uh kind of a a practical example let’s say we have some posts usually it’s an array of objects but let’s just say there there’s some strings post one pose two okay and let’s say we’re getting those from a database or from an API and we want to show them on the page right let’s say we want to show the first post so I’m gonna I’m just going to do a console log you’d probably show this on in the page but for now let’s just do a console log of posts and let’s get the first one all right so I get post one right I’m getting the zero index of this array now if this PO if this was empty like let’s say there’s no posts in the database or whatever and then I go to display this or in this case log it I get undefined so if we were displaying this on a web page you’re not going to want to display undefined so what we could do is before that is add a condition of let’s say posts dot length and let’s say if that is greater than zero then we’re going to use the double Ampersand here now if I save that it’s not going to show this if this if there is no post there right if the posts are empty then it’s not going to show it if I add in here post one post two and then I save now I see post one so this is a very common way of of using this operator we do this a lot in react in the front-end framework react when we’re working in jsx and we’re taking stuff from an API or wherever the the data is coming from and we want to we don’t want to display something that’s not there you want to check first to see if it’s there so if this is false it’s going to show it’s going to return the last value now as far as the double pipe the or operator the way this works is it will return the first truthy value or the last value so let’s say let B and then we’ll console log B and let’s set b equal to 10 and then we’ll use the double pipes and then 20. so in that case it gives us 10 because again it will return the first truthy value or the last value both of these are truthy so it’s going to return the first one if I were to set b equal to let’s say 0 which is falsy and then put 20 on this side then it’s going to return 20 because it will return the first truthy or the last value if I do let’s say b equals and then 0 and then null and then let’s do an empty string which are all falsy it’s going to return the last okay if I put on undefined which is also falsy then it’s going to return that which is the last now as far as other operators we have the What’s called the nullish coalescing operator which is the double question mark it’s not used as much but it is available so the way this work works is it Returns the right side operand so whatever’s on the right side when the left is either null or undefined so let’s say let’s let’s see and console log C and then we’ll do C equals and then 10. the knowledge coalescing operator 20 and it’s going to give me 10. so again it Returns the right side when the left is null or undefined 10 is not null or undefined so it’s going to return 20 the right side if we were to set the left side to either null or undefined then the right side gets returned you can see we get 20. let’s say 30 and let’s do undefined we get 30. now it’s not falsy on this side then it Returns the right it’s just null or undefined so if I do 0 here it’s going to return the zero it’s not looking for just falsy it’s looking for on null are undefined if I do an empty string then it’s going to return that empty string because it’s not null or undefined all right so the there’ll be places where you run into this stuff and keep this you know keep keep the documentation and the code that we write here so that you can look back at it if you need to all right now in the next video we’re going to look at logical assignment all right so now we’re going to look at logical assignment operators and in the last video we looked at logical operators like and and or but we also have assignment operators which look like this so we have the or equals the and equals and then we also have something called the nullish coalescing operator now some of these might not make a lot of sense to you right now because you you can’t really understand where you use them I think that the or the or assignment operator is the most useful here so basically the long version of this I’ll just do an if statement here and let’s define let a and we’re going to set that to any falsy value so we’ll just we’ll just set it to false all right and then in here I’m going to say if not a meaning if it is a falsy value right because it was saying not then let’s set a to whatever let’s say 20 or let’s say 10. okay so this can be useful because you want to check to see if a variable is false or null or anything falsy and if it is then you want to set that to a specific value so the shorthand way of doing this using just the or operator and like we did in the last video we could say a equals and then a or 10. so what we’re saying here is just the same thing we’re doing here if a is falsy then set the right hand side so as you can see it says assigns the right side value which is this only if the left is a falsy value which right now is set to false all right so if I comment this out and I run the if statement all we need to log it you’ll see we get 10. if I comment this out and then I run this it does the same thing we get 10. well there’s a shorter way of doing this using the assignment operator so instead of doing that I can just simply say a and then or equals and then 10. if I comment this out we get the same thing all right if I set this this a to null it’s going to it’s going to get set to 10. if I set it to 0 10 so anything falsy if I set a to 20 then it’s going to stay at 20. this isn’t going to set set it because it’s not a falsy value all right so that that can be pretty useful now with the and assign operator it will assign the right side value only if the left is a truthy value so you probably wouldn’t use this one as much but let me give you the the long version of what we’re doing so we’ll set a variable here let’s say let B and we’ll set that to 20 and we’re going to say if B so if it’s truthy then we’re going to set B to something something else let’s say well you know what we’ll do is we’ll set this one to 10. all right and then let’s console log B and it’s going to get set to 20 because B is truthy again this will assign the right side value only if the left is truthy so using a logical operator we would do B equals B and then the and operator and then 20. okay so if I save that we get 20. this is the same as this and then to make it even shorter we could use the assignment operator so we could say B double Ampersand equals 20. okay same thing but again this probably isn’t you’re not going to use this as much as this because this makes more sense right you’re checking to see if it’s if it’s falsy then you’re setting it here you’re checking to see if it’s truthy and then you’re setting it and there are cases where you could use that now the this right here the double question mark equal this is the nullish coalescing operator so this will assign the right side value only if the left is null or undefined with the or it’s if the left is um is falsy at all so zero an empty string no undefined false so it’s checking for falsy this will only check for null or undefined which you might want you know you might not want to check for zero or an empty string or whatever so the long version of this would be if let’s set up another variable here called C so you’ll say let’s C equals and we’ll set it to null and then we’re going to say if C is equal to null or c is equal to undefined then we want to set C to whatever we’ll say 20. okay and if we come down here we console log C we’re going to get 20 because C is null if we set C to undefined it’s going to be 20. if we set C to false which is a falsy value but it’s not null or undefined then we’re going to it’s going to stay false okay and then the shorter version for that would be C equals and then we want to say C and then the nullish coalescing operator and then whatever 20. so that’s still false if I change this to null then that’s going to change to 20. and then the shorter version of that would be to use the assignment operator like that okay so hopefully that makes sense and it’ll probably be a while before you use something like this in an actual project but I we’re going over you know logic and control and and conditionals so in in different operators so I wanted to include logical operators as well as these logical assignment operators all right so now we’re going to look at something called the ternary operator which you’re probably going to use all the time and it’s a shorter way for writing a conditional so what I’m going to do here first is do a just a basic condition using an if statement and then I’ll show you how to do it with uh with a ternary operator so let’s say using and if statement so I’m going to say if the age variable is greater than or let’s say greater than or equal to 18. then let’s do a console log and we’ll say you can vote else then we’ll console log and say you you can not vote all right so pretty simple if I run that we get you can vote because I set age to 19. if I set it to 13 and say if we get you cannot vote so I want to show you how to write this in a one line one liner using a ternary operator so let’s say using a ternary operator now this syntax is actually really simple but it can it does confuse a lot of people when they’re they’re first learning it so I’ll try to explain it the best I can so there’s basically three parts to it the first is going to be the condition so in this case we’re testing to see if age is greater than or equal to 18 okay so that’s what we want to evaluate then we want to use the ternary operator which is simply a question mark and you can think of this as the if because what comes after this is what you want to happen if this is true right so in this case we want a console log and we’re going to say you can vote right and then for the else is that’s going to be represented with a colon all right so else then let’s do a console log and we’ll say U can not vote if I save that we’re going to get the same result as this all right so three parts we have where we evaluate the condition we have what will happen if that’s true and then what will happen if that’s false so it’s really simple and if I change the age to 20 then both of those should say you can vote now in a lot of cases you’re going to set a value based on a condition you’re going to set a variable value based on it so let’s put a comment here we’ll say assigning a conditional value to a variable using the ternary operator so let’s say we have a variable we’ll call it can vote and we want this to contain we could set it to true well yeah we’ll set it to we’ll make it a Boolean but we want that to be true if the user is 18 or over and we want to be false if they’re under so first thing we want to put here is the condition so let’s say if the age is greater than or equal to 18 then we want our ternary and then next is what we want to put what we want to store in that variable so we could store a string that says you can vote but I’m just going to put a true here because I want that to contain a Boolean all right and then else then we want it to contain false so let’s go ahead and console log can vote and if I save that we get true and then if I change that to let’s say 17 then we get false and it doesn’t have to be a Boolean that you put here you could you could also let’s make this canvo 2. you could have a string that says you can vote and then if it’s if that condition doesn’t pass then we’ll have a string that says you can not vote okay so now if I console log can vote 2. then it has this string you cannot vote that string has been assigned to this variable so you’ll see you’ll see this a lot in all areas of JavaScript now we can also have multiple statements so if we want to do multiple things if we want to do multiple things within the if and the else we can do that as well so first thing I’m going to do is show you the long version of of what I want to accomplish with the ternary so I’m going to create a variable called auth that represents if we’re logged in or not or if we’re authenticated and then I’m going to just create a variable called redirect and I want to set that to something different based on if this is true or false so I’m going to go ahead and just do an if statement first and we’re going to say if off so that’s going to be either true or false if we’re authenticated then I want to do an alert and we’ll say welcome to the dashboard right and then I want to set that redirect variable I want to set that to slash dashboard else then we’re going to alert and let’s say access denied because we’re not logged in and then I want to set that redirect variable to slash login all right and then we’ll just do a console log of the redirect variable here so if I save that we see welcome to the dashboard alert because auth is true so this is going to run and then when I click OK this is going to continue and it’s going to set dashboard into the redirect variable right if I set this to false now if I save we get access denied and we get login put into the redirect variable so we can severely cut down this code using the ternary operator so I’m going to show you how to do that so let me just comment this out and then we’re going to go down here and say const redirect and we want to conditionally set this right so we’re going to evaluate off we’re going to use the well actually I can’t let me just comment that out too so we’re going to evaluate auth whether that’s true or false and if it’s true I want to I want to do two things I want to alert and set the variable so I’m going to put parentheses here and then else I’m also going to do an alert and set the variable so I’m going to put parentheses here so the first thing I want to do if it’s true is my alert so I’ll say alert welcome so I can’t type welcome to the dashboard okay and then I’m going to put a comma after the alert because I want to do multiple things here and I’m going to put in here my string that I want to set which is going to be slash dashboard so that’s the true if it’s false then in here I’m going to do an alert and I’m going to say access denied and then I’m going to put a comma after alert and what I want to set the variable to is slash login so let’s go ahead and save that and you’ll see since auth is false we’re getting an alert that says access denied and when I console log redirect it has login if I change this to true and save welcome to the dashboard and then we have slash dashboard so this does the same thing as this but shorter and its preference when and where you want to use the ternary so let’s see um the last thing I want to show you is that we can use a shorthand we can use the the and operator as a shorthand if there’s no else right because not every if statement not every conditional has an else you might just want to do one thing so let’s say for instance if I come down here um let’s say we want to evaluate off whether that’s true or false and if that’s true then I want to do a console log and just say welcome to the dashboard in my console else then nothing I don’t want to do anything else so in this case if we’re using the ternary oops I’m sorry that should be a colon if we’re using the ternary we need to have an else I can’t just do this if I do that I’m going to get a syntax error so I have to have an ounce but if I don’t want to anything to happen I could do this I could say no right so now it’s going to let me just comment this out because I don’t want to keep getting that alert okay so we see welcome to the dashboard because this is true if this is false then we’re not going to see anything because I just set this to null but a shorthand to this if you don’t want to do else null is to use the double ampersamp the and operator so I can say auth and then double Ampersand and then console.log and then welcome to the dashboard and then I’ll comment this line out and save doesn’t do anything right now but if I set this to true then we see welcome to the dashboard so this this comes in handy a lot I use this a lot when using react with jsx if you don’t know what that is don’t worry about it but it’s it’s very convenient and very compact all right so that is the ternary operator hopefully you understand this so let’s move on to the next video all right guys so most of the stuff that we’ve done has been pretty basic aside from a few things like scope and execution contacts Etc now we’re going to step it up a little bit and learn about loops and iteration as well as some high order array methods which are methods that we can use on arrays that take in a function as an argument and we can use these methods to Loop through or iterate through arrays and do specific operations on each element and these These are methods that you’ll be using all the time in JavaScript so this section is is really important and after this in the next section we’re finally going to get into you know being able to show stuff in the browser and get into the document object model events and all that stuff and now you’ll be more comfortable doing that where now you know the fundamentals of JavaScript syntax all right so let’s get started with loops all right so we’re going to be looking at Loops in the next few videos and a loop is a control structure that provides a way to do iteration in programming and iteration is a process where you repeat something over and over again until a certain condition is met or until a certain condition is not met and this can help automate tasks and so on and there’s many different kinds of Loops in programming what we’re going to look at right now is one of the more common ones and this is a for Loop all right so this is the syntax right here this is an actual code but this is how it’s formatted and I’ll create a real for Loop in a second but just to show you what goes in here so we have four and then we have some parentheses and three different Expressions that are separated by semicolons which are a little weird you probably mess up and use commas but it’s going to be semicolons here now the initial expression is where we initialize a variable or counter to use within the loop and then the condition expression is going to be the condition that the loop will continue to run as long as that condition is met so as long as this is true it’s going to run once it’s false then the loop will no longer run and then we have the increment expression which is going to be executed after each iteration of the loop okay every time it Loops that’s called an iteration it’s going to run after every one of those and it usually increments the variable because if you keep your your variable or your counter the same you’re going to have an infinite Loop you need to increment that and then the statement is just going to be your code executed and you need to use curly braces like you would a functioned to execute a code block all right so let’s just comment that out because that will break our script and then we’re going to come down here and let’s create a for Loop okay so just like a function parentheses and curly braces then we want our initial expression which I’m going to say let I I is very common very common variable to use in Loops so we’ll say set that to zero then we want to put our semicolon because these three expressions are separated with a semicolon the condition that I want this loot the code to run as long as this is met is going to be as long as I is less than or equal to 10. okay so as long as that condition is met this Loop will run and then lastly here I’m going to put in the increment expression which will be I plus plus so we learned about that in the past video this will just increment by one all right so basically it starts at zero it’s going to go through then it’s going to increment by one so I will then be equal to one it’s going to go through again it’s going to run whatever code we put in here every time up until this is no longer true so let’s just do a console log in here I’ll just put a string we’ll say number and then I’m just going to concatenate on the I variable and we’ll save that and run it and you’ll see we’re going to get number zero all the way up to number 10. now it stops here because it it no longer meets this condition it goes through the this last time and says well now I is is doesn’t match this it’s not less than or equal to 10 so we’re not going to run this again okay if I change this to 11 and save then it’s going to get it’s going to go up to 11. if I change this initialization here from 0 to let’s say five and then I save it then it’s going to start at 5. all right uh and it’s gonna it’s gonna just increment by one each time if I wanted to I could do something like I equals let’s say I plus two if I save that then we get 5 it’s going to skip six seven skip eight nine so it’s basically incrementing by two but most commonly you’re gonna see this and let’s just set that back to zero and let’s set this back to 10. now you might be asking why I’m using let because you know that I use const unless I I can’t so in this case if I were to use const here and save that I get assignment to constant variable because remember we’re initializing I here is zero but it’s going to get changed in every iteration so we can’t have this as a constant we use let now I also showed you in a past video that we have block scope here right so if I come outside of the loop and I console log I I’m going to get an error unless I use VAR because remember VAR is not block scoped so if I do that then I’m going to get 11 but I would highly recommend that you use let when you use when you you know create for Loops now you’re going to have situations where you check to see if I is is equal to something or greater than or less than something and maybe do something else based on that so for instance if I want to say put in an if statement here and if I say if I is equal to 7 and then let’s say I just want to output and say 7 is my lucky number so I want to Output that if it’s seven and then if I didn’t want number seven to show I just want this 7 is my lucky number then I could put an else and then move this into here so now if I save that it’s not going to show number seven it’s just going to show 7 is my lucky number instead now there will be times where you will Nest Loops so I’m just going to show you that real quick and it can get a little confusing when you have you know multiple levels of Loops but just to give you a simple example let’s do the same thing here where we set I but let’s set it to 1 and say as long as I is less than or equal to 10 and then I plus plus we want to increment by one and we’ll do the same kind of console log thing here but still within this Loop I’m going to open up another for Loop now when you do this you want to make sure you don’t use I again you want to use something different and it’s common to use J so we’ll say let J equals one I’m going to do the same condition here I’ll say as long as I is less than or equal to 10 and I’m sorry j you don’t want to do that you want to do J yeah or else you’re gonna get an infinite infinite Loop and then let’s increment J and then in here what I want to do is show I want this to do the console log like we already have here starting at one and under each number here I want to show that number times one that number times two all the way up to 10 that’s what this represents right here so let’s console log a string that actually says like one times one equals one in one times two equals two Etc so we’ll use a template string here and I’ll say I and then we’ll just put a asterisk here times J and then an equal sign and then the actual expression to to be evaluated is going to be I times J so if I save that what we’re going to see is the well actually let me comment this one out we’re going to see number one and then under it one times ever all the way up to 10 then 2 and then two times all the way up to 10 and that’s because of this if I change this 10 to a 5 then it’s going to show 1 times 1 all the way up to five for each of these all right and we could do as many as we want if I put this first one to a hundred it’s going to show me all the way up to 100 and it’s very fast so that’s a nested Loop so let me actually should say nested loops and what I want to show you now is how we can use a for Loop to Loop through an array now I don’t do this very much because there’s a for each method that we can use it’s a high order array method we’re going to get into in a couple videos from now that we can use to Loop through arrays and do the same thing but it is possible to use a for loop as well so let’s say we have names or whatever anything you want to put into an array I’m just going to put a bunch of strings here names and we’ll say John and I don’t know Tim okay so we have some names now to Loop through this I’m going to say four I’m going to initialize my variable so we’ll set let I set that to zero and then here for a condition we can say as long as I is less than is less than the length of the array so we’ll say names dot length and then we need to increment I so we’ll say I plus plus and then within here we can access each one by its index I is now going to represent its Index right because it starts at zero so this will be zero then that’ll be one two three and four so let’s just console log each one we’ll say names and then we’ll put the I as the index in here and I’ll save that and now you see it’s going to Loop through and it’s going to show each name now those of you that are just learning this for the first time I want you to try a little challenge so pick a name here let’s say Sarah and instead of just printing Sarah have it print Sarah is the best so if you want to pause the video and try that out you can do that now but basically all we have to do there’s a few ways we could do it if we know the index which we do we know Sarah is in the zero index so we could just say if I is equal I’m sorry the two index if I is equal to 2 then let’s do a console log and we’ll just say names I which is just going to say Sarah and then we’ll concatenate onto that a string and say is the best else then we just wanted to log the name so I’ll put this up here oops whoops and save and now it says Sarah is the best so you could do it like that you could test for the value so we could say if names and then I if that is equal to and then the value let’s say we want to do John is the best then we can check for John and now you see it says John is the best all right so that’s pretty much the basics of for Loops now you’re probably going to have times where you run into something called an infinite Loop that’s a loop that just keeps going and never stops until it crashes your browser in this case and that can happen if you mess up the condition or if you if you forget to increment if you want to test it I wouldn’t recommend it but if you want to test it you’ll just have to most likely force close your browser but you could put Infinity here so if I did that obviously I is always going to be less than infinity that means that this is always going to run but I’m not going to do that so you probably will run into Infinite Loop set some point or another but in the next video we’re going to talk about the break and continue statements all right so now we’re going to look at the break and continue statements so this should be a pretty quick video basically what break does is it allows us to do just that break out of the loop so usually you’re going to check for a specific condition and then you’re going to break out so let’s say we’ll set I to zero let’s say as long as I is less than or equal to 20 and increment by one and then let’s say we’ll just do a console log of I if I save that you’ll see it’ll just show 0 through 20. but let’s say we want to stop once we hit 15 so I’ll just do a check here and say if I is equal to 15 then we’ll console log and let’s just let’s just say breaking and then right under that we’re going to put our break statement so just break semicolon we’ll save and now you can see once it hits 15 it’s going to break and it it just doesn’t go on any longer alright so you might have cases where once you hit a certain condition there’s no need to keep going you just break out of the loop all right now I’ll continue is a little different so with continue continue basically you can you can skip uh the rest of the code in a current iteration and then continue to the next iteration so for instance if we do the same thing here we’ll say let I equals 20 and as long as I’m sorry let I equal zero and then as long as I is less than or equal to 20 we want to increment and we’ll do the same thing just console log I let me just uh let’s comment this out here okay so we just get 0 through 20 and let’s say where a superstitious hotel and we want to skip the 13th floor so let’s say if and say I is equal to 13. then let’s do a console log and we’ll say skipping 13 which I think is crazy and then we want to just continue all right so what’s going to happen here if I save this as you’ll see it’s going to skip 13. so instead of like I could I could have the same effect if I did this if had this console log and then else had this console log but here I’m I’m just going to skip the rest of this right so whatever is going on down here it’s going to skip because of this continue so here it breaks out of the entire Loop right here it breaks out of the iteration and then continues on okay so hopefully that makes sense all right so now we’re going to look at two more types of Loops the while loop and the do while loop and these along with the for Loop are kind of like old school ways of doing iteration now that we have high order array methods we have four each and then there’s also other Loops like four in and four of which I’m going to go over as well but it still is essential that you learn these because these are like fundamentals and not just in JavaScript in just about every language so with a while loop it’s a little different because all that we put in here is the condition when we initialize and increment the variable we don’t do it within these parentheses this is just the condition so I’m going to initialize the I variable outside of the while loop and then in here I’ll put the condition say less than or equal to 20. and then I’ll console log let’s just put a string number and then concatenate that number now this can be easy to forget the increment and then have an infinite Loop because it’s not as obvious whereas a for Loop you know you have the three parts to pass in here you just have to remember to increment so let’s save that and now it’s going to print out 0 to 20. okay so that’s the syntax of a while loop now for many cases you could use either a while or a for Loop and achieve the same result as you can see it’s very similar it’s just different syntax but a common rule that many programmers follow is to use a for Loop when you know the number of times that you want the loop to run and then to use a while loop when the number of times the loop will run is unknown okay that’s not a mandatory convention or anything but that’s something a lot of people do we can also use while Loops to Loop over arrays just like we could use for Loops I’m just going to comment this one out and then let’s say const array we’ll set that to let’s say 10 20 30 40 and then in here we want our condition expression so let’s say while I is less than the array Dot length then we’re going to console log and we’ll say array we want the index to be the I variable and then this is really important you want to add your increment are you going to get an infinite Loop so if we save that now we’re going to see 10 20 30 40. so it’s printing out the values of this array if I add 50 that’ll get added as well now another thing that we can do is Nest while Loops just like we can for Loops so let’s say Nest nesting while loops and we’ll do the same thing we did before we’ll have the multiplication thing so let’s use I so we’ll say as long as I is less than or equal to Let’s do 5. and then in here we’ll just console log we’ll say number and plus whatever that I variable is and then in here I need I’m going to Nest another while loop so I need another variable right so we need to initialize another variable so I’ll use J and set that to 1. and then let’s say while and we want to say while J is less than or equal to and this is for the multiplication part so let’s do five we’ll do up to times five and then in here we’ll do our console log and we’ll make this a string where we can say I times J is equal to the expression of I times J now this is really important we need to remember to increment both J and I so let’s say J plus plus and then back outside into the parent Loop we want to do I plus plus all right so let’s go ahead and try that and now you’ll see it’s going to Loop through five right one through five actually it’s going to start at zero because of this we can set that to one so now it’s going to start at 1 and it’s going to show one times one through five then two two times one through five three four and then 5. okay so that’s how we can Nest a while loop now do while Loops are a little different because the do while loop will always run at least once even if the condition is false so the answer to the question when would I want to use a do while loop is when you always want the the block of code to run at least once even if the condition is never met so let me show you what I mean I’m going to comment this out and then let’s do let’s say do so this is the syntax we we say do no parentheses after it just just uh curly braces and then whatever we want to happen let’s say console log and number and concatenate that and then we want to increment so I plus plus and then here is where we’re going to add while and then that’s where we want to add our condition so let’s say while I is less than or equal to 20. okay and I don’t know why I open parentheses here um for curly braces we don’t want those all right so this is a do while loop so let’s run this and as you can see we get we get 1 through 20. remember this is set to 1. now like I said the thing with this is this code right here is always going to run once even if this is never true so if I were to come up here and set I to 21 that this is this condition is never met however if I save this I get number 21. so it runs this code here no matter what so that’s that’s the big difference with this if I uncomment this uh where is it this right here where it says I is less than or equal to 21 and I comment out the do while and save we get nothing right because this condition here is never met this is 21 so this is not whoops this is 21 so this is never going to run or this code is never going to run do while it’s going to run once then it’s going to check and see if it’s to run again so that’s the big difference and and you can also use break and continue statements with these Loops as well just like you can with a for Loop all right so when you go to get a job as a web developer and you go to different interviews you may be given specific programming challenges to do on the computer or on a whiteboard and it’s good practice to do challenges like this not only for job interviews but it also just sharpens your skills in general and you’ll find that most challenges have some kind of iteration involved and one of the most common ones that you’ll run across is called fizzbuzz and this has to do with loops and conditionals so I think that this is a good point in the course to do the fizzbuzz challenge and it’s not very difficult we’ve we’ve already gone over everything that you need to know so as far as instructions you need to print or log the numbers from 1 to 100 you guys know how to do that easily and you can use different types of Loops if you want you can use for a while whatever and then for multiples of three you want to print Fizz the word Fizz in a string instead of the number for multiples of three for multiples of five you want to print the word Buzz okay instead of the number and then for numbers which are multiples of both three and five you want to print Fizz Buzz okay so as far as hints go if you’ve taken the course up to this point then you know how to write a loop and output or log something for each iteration right so you can print the numbers you also know how to check for a condition with if else else if you also know how to get a remainder of a number using the modulus operator which is the percent sign and this is really all you need to know to complete this challenge I probably already told you too much now if you don’t get it don’t worry about it some people including myself are not that great with these types of challenges especially if you can’t you know do any research so try not to go and and Google fizzbuzz challenge try this on your own and see if you you can figure it out all right so let’s get to the solution now I’m going to show you I’m going to show you how to do this with a for Loop and a while loop so first thing we want to do is print or log the numbers from 1 to 100 which is very simple so we’ll say 4 and let’s initialize I with one because we’re doing one to a hundred the condition is going to be if I is less than or equal to 100 and then we want to increment I by 1. all right and now in here for now let’s just console log I so it should just print 1 to 100. so the next step is to print uh print the word Fizz for multiples of three now the way that we can figure out if it’s a multiple of three is if if the remainder is zero and we can find the remainder using the modulus operator so here let’s say if and we’ll say if whatever that the current number is on the current iteration and then modulus 3 if that is equal to zero then we know it’s a multiple of three so in that case we’re going to console log Fizz and then let’s just do else and then we’ll move that console log of the number in there so if I save that and we come up here you’ll see that three is Fizz 6 9 12 15 and so on now if it’s a multiple of five we want to print the word Buzz so what we can do is put let’s go right here and say else if or l space f and then open up a curly brace and end our curly brace and then in here we want to say if I and then again we’ll use the modulus operator but 5 this time if that’s equal to zero then we want to console log the word Buzz so let’s save that and now if we look you’ll see that 5 is Buzz right 10 is Buzz but if we look at 15 it says Fizz and that’s because 15 is a multiple of three and five and since this conditional was first then it’s going to log Fizz so for the condition of of looking for them both we can’t do that under these ones because it’s going to check those first so we have to make sure that the first one we check is is for both right so what we’ll do is instead of putting this as an if we’re going to make that an else if and then we’re gonna it will just push that over and then we’ll have our initial if statement here like that and then we can say if I modulus 3 equals zero and if I modulus 5 is equal to 0 then we want a console log Fizz Buzz alright so save that and now if we look we’ll see 3 is Fizz 5 is Buzz 6 is Fizz nine is Fizz 10 is Buzz 12 is Fizz fifteen is fizzbuzz the next one after that should be 30 is fizzbuzz next one after that should be 45 is fizzbuzz all right now a shorter way to do this since 3 times 5 is 15 that means that any uh anything that’s divisible by 15 is is also going to be divisible by both three and five so we can actually shorten this to just say I’m sorry that’s not what we want we want that to be zero but we want this to be 15. all right if I save that we should get the same result so Fizz buzz and then 15 fizzbuzz 30 fizzbuzz 45 fizzbuzz 60 say and so on all right so that’s the solution with a for Loop now a while loop is going to pretty much be the same thing we’re going to have the same conditions it’s just formatted a little different so let’s say while loop and remember with a while loop we need to set the variable outside of the loop I’m going to use J for this since we already used I and I’ll say even though I was scoped but I’ll say let J equals 1. and then we’ll say while J is less than or equal to 100 then we want to do this this block right here so I’m going to grab that paste that in now remember with a while loop it’s it can be a little hard to remember that you have to increment so make sure that you go outside of that if and you just increment I by one so I plus plus all right so let’s save that uh whoops I’m sorry that should be J so here yeah let’s change that change that to J that and that and this all right so now actually let me comment out the for Loop so that doesn’t run and we should get the same result so three Fizz six five Buzz six Fizz get to 15 we get Fizz Buzz we get to 30. we get Fizz Buzz okay so this is how we would do it with a while loop but basically the same thing it’s just a structured in a different way all right so if if you got it great if you got it and it’s it’s a slight different slightly different from mine that’s fine if you didn’t get it that’s fine as well um you know you’ll you’ll learn more as we move along all right so in this video we’re going to look at a four of loop which is a newer way to basically Loop through iterable objects like arrays or any even strings and maps and sets which we haven’t talked about yet not object literals there’s actually another loop called a four in that we’re going to look at in the next video to show you how to Loop through objects but this is a cleaner way to Loop through an array than a standard for Loop or a while loop so let me just create an array here we’ll just do items and we’ll put some random items in here let’s say Book Table chair and kite and then I want to Loop over these now if you remember with a for Loop what we would do is we would initialize a variable here set it to zero and then we would do as long as I is less than whatever that array length so items dot length and then we would increment that I variable and then if we want to access each specific item we would have to do items and pass in the the variable as the index all right now A Cleaner way to do this is with four of so instead of doing all this in here we can simply do I’m using cons but you can use let if you want but we can simply say const and then give a variable name for each individual item which I’ll just call Item and then say of items all right and then in here I don’t need to do this because we can just simply access the item variable if I save that and run it we get the same result and this is much cleaner and just much more modern looking and if we wanted to have an array with objects in it like let’s say users and we’ll set that to let’s say an array of objects and we’ll just give these a name so we’ll say name Brad and a couple more here I’ll say Kate and say Steve all right and then let’s comment this out and we’ll say four and we’ll call we’ll say for const user of users and then I’ll console log user okay so now we have all of our objects if I want to access a specific property then I would do user Dot and then whatever that property in this case name now my first choice for looping through arrays is to use the for each method which is a high order array method that you can use on that you can use directly on arrays but I think this is a better way to do it than using a standard for Loop or a while loop or a do while loop or anything like that so we can also use this to Loop over strings okay let me just put a comment up here and I’ll say Loop through arrays all right now for Strings let’s say const and we’ll just say Str and we’ll set that to let’s say hello world and then if I want to Loop over that I can simply do four and then give a variable let’s just say letter because that’s what we’re going to get is a letter and then of our string and then if we console log here letter and save then you’ll see it’s going to Loop through and it’s going to Output each letter of that string another thing you can do is Loop over Maps which we haven’t talked about yet I’ll get into this later on but just to give you a quick example we can create a map a variable called map and set it to a new map not a nap although I could use one of those but we’ll set it to a new map and then we can add key value pairs so I could do map.set and we could set let’s say name to John and then I could Set Let’s do an age so we’ll say age 30 and if I wanted to Loop through these I could do a four of so I would do cons now we can get the key and the value by putting brackets in here and just saying key value of the map and now if I console log here I’ll go ahead and log both the key and the value and now you’ll see down here both the key value pairs name John and age 30. so you can use it to to Loop over Maps as well pretty much any iterable object now there is another type of loop called for in that allows you to Loop through object with object literal values which we’ll talk about in the next video all right now there may be times where you want to actually Loop through an object’s values and we can do that with the four in Loop so let’s go ahead and create an object here I’m just going to call this color object and set that to some curly braces and then we’re going to do color one set that to a string of red and we’ll do that for a few colors let’s say color 2 is going to be blue say orange would be color three color four we’ll do green all right and we want to Loop through and get these colors so a four in Loop is very similar to a four of loop so we would just say four and then inside here we’re going to say const and we can get the key so if I do key in color object and then we console log that key we get color one through color four so we get the keys now if we want to get the value all we have to do actually we’ll just log it here is take the color object variable and then pass in here the key if I do that then you can see we get the values red blue orange and green now let’s say we want to use this with an array because we can we can use four in loops with arrays so we’ll say const and say color array and we’ll set that to an array with red green blue and let’s say yellow all right so we have this array of colors and I’m going to do this so we’ll say four and then we’ll do cons let’s say color uh not of we’re going to do an in so in the color array and then let’s console log color if I save that we’re actually going to get 0 1 2 3 instead of this so what’s happening here is it’s giving us the keys okay it’s giving us the keys which are in this case these are going to be numeric Keys 0 1 2 3. so we can still get the values of an array here but what we have to do is let’s change color let’s change that to key and then we can say color array and then just pass in the key like that if I save that and run it now you can see we’re getting the values of the array so you can also there’s so many different ways to iterate through arrays but this is most commonly going to be used if you want to get the the either the keys and or the values of an object literal so now in the next video we’re going to start to look at high order array methods which are extremely helpful and you’re going to be using them all the time within JavaScript and we’re going to start with four each all right guys so now we’re going to get into high order array methods in this particular video we’re going to look at four each but there’s a lot of these that can do different things now they all work in a similar way in that they take in a function as an argument which this is called a callback function and in that callback function we can pass in a variable for each element in that array or each item in that array now what a 4-H does is it just simply Loops through it doesn’t return anything it just Loops through as if we were using a 4 or a four of loop to just go through the array and do something specific all right so let’s go ahead and jump in here and we just want to create an array of some sort I’m going to call this socials and I’m just going to have a bunch of strings in here so Twitter let’s say LinkedIn do Facebook and let’s do Instagram all right so we just have an array of strings and this could be an array of anything and before I show you the four each I just want to console log here socials and then the Prototype chain which is double underscore Proto double underscore and I think I showed you this back when we looked at some of the simple methods like push and pop so you can see that those are here as well so any any methods or properties like length on the array are going to get shown here and you can see we have four each right here we have map map filter find reduce these are all high order array methods and they work in a similar way so basically let’s go ahead and comment that out for now basically what happens is we call the method so in this case four each and then that method is going to take in a callback function okay an anonymous function it’s not going to be named and we can do that in a few different ways we could just use the standard function syntax and then what gets passed in here if we look at this documentation page here what gets passed in you can call it element like they did here but you can call it anything it just represents each item in the array okay so here we just have ABC for us we have these strings here so you can call it I mean a common thing I’ll do is call it the singular version of the array or I’ll call it item I don’t usually use element but again you can call it whatever you want and then you have access to that in here so we can do console log item okay so this this function right here that we pass in is going to get run for every element or every item that we have in the array so in this case it’s going to get run four times and what we’re doing is just logging it to the console so if I save that and we take a look we should see these in the console all right and if you want to kind of slow it down a little bit you could go to sources and go to script okay we looked at this debugger back when we looked at execution context and the call stack but what I’m going to do is put a break point right here on the four each and then I’m going to reload the page okay so it nothing is run yet but if I come down here to the step arrow and I I hit that and then it’s going to go into the function we’re going to run the four each I’m sorry run the console log and now we get Twitter okay if I go back again it’s going to run console log again because there’s another item in the array again Facebook again Instagram and then it’s going to end because there’s no more items in the array okay so that’s kind of a step-by-step of what’s Happening let me just remove I just want to remove that break point there all right and then we’ll go back into the console now like I said you could pass in a function this way or let’s actually comment that out or you could first of all get rid of the function keyword and then add on our Arrow so this is valid but since it’s just a one line expression we can actually take away the curly braces as well if I save that we get the same thing now in addition to the item that we pass into the Callback there are some other arguments that we can pass in so I just want to go back here and we’ll come down so these are the parameters right we have our callback function and then in that callback function we have the item our element but in addition to that we can also pass in the index of the current element being processed in the array and of course it’s going to start at zero the array so we can also get the entire array there might be times where you need that within your your function so let’s go ahead and pass in the index and then we’ll pass in the entire array so those are the additional parameters so here what I’ll do is I’ll console.log let’s just put in some backticks here and of course we need to wrap the item in that and then let’s also do before it will do the index and then slash so we’ll say index Dash and then the ice Dash not a slash and then if we look here you can see the index starts at zero and then increments and then let’s pass in after the back tick here we’ll just pass in the entire array so you can see that you have access to to that as well now you can also pass in a named function rather than an anonymous callback so for example let’s create a function called log socials and that’s going to take in an item or we can just say like social and then we just want to console log social so we want this function to run for every item that’s in the array so what we can do is just take socials call for each and then simply pass in log socials all right if I save that let’s just comment this one out if I save that you’ll see it’s going to log all the social items here now when you pass this in you don’t want to execute it right you don’t want to pass in the the parentheses you want to just pass in the definition of the function just like you do here you know you don’t you don’t execute this function here it’s a callback now the last thing I want to show you is with objects because usually when you pass when you use for each it’s usually on an array of objects so let’s say social objects and we’ll set that to an array and each object will have let’s say a name say Twitter and the URL say https twitter.com and then what we’ll do is copy this down a couple times and let’s change this one to Facebook and what else LinkedIn and Instagram all right and and you can have I think I think I mentioned this before but you can have trailing commas in your arrays in fact if I save prettier automatically keeps the trailing comma so I want to comment this one out and then I want to log each item here so let’s say social objects and then Dot for each and then we’re going to pass in our function which is we’ll say item and then let’s just do uh console log of that item so in this case it’s going to give us objects right each each item in the array is a social object so if we want to access a specific property specific property we would do item Dot and then whatever let’s say URL so now it will give us all the URLs and then of course we could do whatever we want to that array and we’ll be using for each a lot more but in the next video I want to show you an example of another high order array method called filter okay so now we’re going to look at filter which is another high order array method for each is usually the first one you learn now the difference between four each and a lot of these other ones we’re going to look at like filter and map is that filter along with a bunch of other high order array methods actually return something in most cases they’re going to return an array now our modified array so if we look at this example at on mdn you can see we have some words in an array and then we have this variable result set to words.filter so this is something that you’re going to do because this returns something right for each does not so you’re typically not going to see a variable equal to something dot four each you just run that for each and then you do whatever you want in the function in this case what’s going to happen is we pass in a function okay this is a function I know it looks a little weird because there’s no parentheses around this but remember with arrow functions you don’t need to have parentheses if it’s just one parameter so what we’re saying here is We’re looping through we get can get each word and then we’re testing that word and seeing if the length is greater than six Okay now what’s this is going to return this line right here is an array with only the words that pass this test or only the elements in the array that pass this test so the result will be these words right here because they’re greater than six if they’re not then they’re not going to be put into that array so we’re filtering out the words that don’t pass this test okay so let’s uh let’s try this on our own so that it’s more clear so we’ll say cons numbers and I’m going to set this to let’s just do one through ten nine and ten and then let’s say I want to filter out and I only filter out all the odd numbers so I just want the even numbers now I’m going to create a variable because it’s going to return something so we’ll say let’s say even even numbers and we’re going to set it to the numbers array dot filter and again this will take in a function I’ll just do a long form for now so we can say function and pass in here whatever whatever variable we want to use for each individual element or number so I’ll just say number in this case you could use item or whatever now what we want to do here is return from this function some kind of condition now if I want to get the even numbers I can do this I can say if the number and then modulus operator and then 2 if that is equal to zero so if it’s divisible by 2 then obviously it’s even right if we have zero remainder then it’s divisible by 2. so this is going to Loop through run this test on each of these and whichever ones pass will be put into a new array in this variable so let’s go ahead and console.l log here even numbers and if we take a look in our console you can see we get 2 4 6 8 10. if I add on to this 11 and 12 then 12 should be added now this is kind of the long way of doing this the shorter way let’s say short version and then I’m just going to comment this out so the short version would be to do even numbers equals numbers Dot filter and then we could pass in here just number use an arrow and then we just want uh the condition which is if the number modulus 2 equals zero save that we get the same thing okay now if you wanted to do this with a 4 each let’s say same with four each it’d be a little more complicated right if you want to pause the video and try it you can but let’s um let’s take numbers right and then do a four each so we can’t we’re not going to set like anything equal to this this is just to Loop through so what we can do is initialize a variable here we’ll just say let even numbers and then we can Loop through here and say number and then we’re going to have to do an if statement here if we want to test right so we’ll say if the number modulus 2 equals zero then we’re going to take the even numbers uh even numbers variable which is is uh you know we want to set this to an empty array so you can see how much more complicated this is then we would have to push onto it the number if it was even right so now if I save and we’ll get the same result so this right here this one line is the same giving us the same as this right here all right and we could use const here since we’re just pushing on we’re not reassigning anything yeah so that’s filter now I want to do this with uh an array that’s slightly more complicated with some other conditions other than just testing for an even number so let’s comment this out and then what I’m going to do is grab the array so we’re just going to use an array of of company objects all right so each company has a name a category a start date and an end date so if you want you can look at this as a challenge and pause the video and try to try to do this they’re all just using filter but the first one the first thing I want to do is get only retail companies okay so I just want companies where the category is equal to retail so if you want to pause the video and try that go ahead and do it now but what we’ll do is create a variable let’s say retail companies and you you can you can imagine how useful this is you know if you think about a UI where you’re filtering things this comes in handy so let’s say companies okay we want the company’s array and we want to filter and then we’re going to use a short form Arrow function so let’s say company so for each company we want to test if the company Dot category because it’s an object so we want to access the category and say if that is equal to the string of retail all right so now if we console log retail companies we should get three three values and let’s take a look here so we have company two company four and Company nine all right so if we look here company two is retail company four is retail and Company 9 is retail so let’s do another one let’s say let’s say we want to get get the companies that started in or after 1980 and ended in or before 2005. okay so companies get companies that started in or after 1980 and ended in or before 2005. okay if you again if you want to try it you can do that I’m going to create a variable we’ll just call it early companies put a space there early companies and we’re going to set that to again companies Dot filter and we should probably comment this console log out all right so companies filter and in here we’re going to have a function pass in our variable of company that’s our item and then we want to test to see if the company dot start is greater than or equal to 1980 right and then is that a string no it’s not a string and okay so we want to use the the double Ampersand the company dot end is less than or equal to 2005. so that should do it so let’s console log early companies and save and we get three so if we look at these it’s company 1 7 and 9. so company one was 1981 to 2004 company seven uh was 86 to 96 and Company 9 was 89 to uh what was it I’m sorry 80 81 to 89. so those were all in the in the realm of 1980 to 2005. these are the ones like this was the 2008 um this one was 2007 2010 so it filtered out by this this condition right here this truth test and then the last one we’re going to do is to get companies that lasted let’s say lasted 10 years or more so to do that we’ll say const and I’ll just say long companies and set that to companies dot filter and we want our function here and it’s gonna I’m gonna say company and then the truth test we want is the company dot end minus the company dot start is greater than or equal to 10 that means that it lasted 10 years or more so let’s console log long companies and let’s let’s comment this log out and you can see we get nine one two three four five six seven eight nine uh oh this should be minus okay so we get five one two four six seven so if we look at like three that only lasted what 99 to 2007 so that’s not quite 10 years what else uh four or five didn’t last 10 years 2009 to 2014. so yeah so hopefully this gives you an idea of how Filter Works this is very useful and we’ll you’ll use it all the time in your interfaces you know when you have a a search box and you’re filtering down by whatever it is location or anything like that this is going to come in handy all right now in the next video we’re going to look at map which allows us to basically return an array just like filter but we can return we can modify anything we want and return an array of anything we want all right so in the last video we looked at filter which is a high order array method and we saw how it returns a new array and it that’s based on a function that returns true or false anything that was true would be put into that array with map this works a little differently where the function what that we pass in can return anything that we want to be put into this new array in this example let’s make it a little bigger in this example we have some numbers in this array one variable and then we’re setting this new variable of map 1 to that array dot map and we’re saying for each value they’re using X here but you could use anything we’re taking that value and multiplying it by two so they’re doubling it and then that will get put into this new array so essentially what we’re doing is taking this array and then we run it through map and then we have an array of these numbers doubled okay so what I’m going to do is give you a similar example and then we’ll we’ll use the same companies array that we used in the last video and do some stuff with that so let’s just create a numbers variable and we’ll set this to we’ll just do one through five and then let’s create a variable here we’ll call it doubled numbers make it a little bit more specific than the the docs and then we’ll take the original numbers array and do a DOT map that’s going to take in a function and we’ll say for each number then we want to return and you could either do the short syntax or you could have curly braces and you could use the return keyword but this is shorter and cleaner so let’s say number times two all right then we’ll go ahead and console log here the doubled numbers and if we go and we look we should see 2 4 6 8 10. now the what I’m returning from eat from this function for each of these elements is each one times two but it could be anything like for instance if I wanted to return a string that had number space and then concatenate the number if I do that you’ll see now it’s going to run through the array it’s going to Loop through and take each one and just prefix it with the string of number so now I have an array of that so you can do absolutely anything here if I wanted to multiply it by 3 and triple it we could do that as well all right now if you wanted to do this with a four each I think it’s useful to know how to do that so let’s say same same with four each so just like we did with Filter when we used a 4-H we have to first just create a variable let’s say double we’ll say double numbers two set it to an empty array and then we could take the original numbers array and loop through so in here we want to say for each number then we’re going to take the double numbers to variable which is an empty array and push onto it the number times two and then if we console log double numbers two uh oh I said doubled oh yeah let’s do double numbers too and now you see it’s the same exact thing so this this line is a shorthand for doing this but now what I want to do is use that companies array that we used in the last video to do a couple things and again if you want to pause the video and do some of this on your own you can do that as well I would encourage that so let’s say we want to get or let’s say create an array of company names okay so just us an array with just the company name no objects or anything just strings so let’s say const company names and we’ll set that to companies which is our array of objects and then we want to map through and have a function where we say for each company we just want to return the company dot name okay so that’ll run for each element each object in the array and get put into a new array so then let’s console log that new array and there we go so now we have just a simple array that has all of those company names inside an array with just numbered indexes now let’s say we want to create a new object that has just the the company and the category so let’s say create an array with just company and category so if you want to pause and try it now you can do that so I’m going to call this company info and let’s set that to companies dot map and say for each company Let’s uh I’m just gonna put a code block here because I’m going to return an object I could just use parentheses and put my object in that but instead I’m just going to say return an object and then name is going to be the company dot name and then category is going to be the company Dot category okay and then we’ll go ahead and console.l log company info and let me just cut let me comment that one out and you can see now we have an array with all of the companies but only the category and the name okay because that’s all we chose and there’ll be plenty of times where you’ll have uh you’ll have a bunch of data but you want to strip some of it out like maybe you don’t need the start and end dates so you can simply manipulate that array or I mean this this will create a shallow copy and then you can manipulate that array to have whatever you want in it now let’s create an array of the length of each company in years so let’s try that we’ll say create an array of the length of each company in years so it’ll just be an array of numbers so for that let’s say const company years and let’s set that to companies.map and we’ll say for each company for each company I just want to take the company dot end date and just subtract the company Dot start date actually you know what let’s make this a little more complicated let’s say create an array of objects with the name and the length of company in years so instead of doing what I just did I think this is a little better this will yeah so we’ll do that we’ll say return an object with the name so we have access to company with all the properties so name and then let’s create a new property called length and that’s where we’ll take the company Dot what is it company dot end subtract the company dot start okay so now let’s do a console log of company years and now we should have objects with the name and the length of year so 23 16 all right and we could even just concatenate in here space years so 23 years 16 years and just to validate that if we look at company one it was from 81 to 2004 so 2001 would be 20 and then we have three more two three four yep so that is correct all right now another thing that you can do is chain let’s say chain map method so you can have more than one map method let’s say we want to square root we want to take a number we want to get the square root and then double it so I’ll call this Square we’ll say square and double and what we’ll do is we’ll set that to numbers dot map and the first thing I’m going to do is is square it so we’ll say for each number we want to use the math object and then we’ll use sqrt so square root that number right so right now if I console log this let’s say Square and double so if I do this right now it’s just going to give me the square root right now I want to double it so what I could do is add an additional map so this map which ends right here just to make this a little cleaner looking I’m going to put this dot map on the next line this is what you’ll commonly see get rid of that semicolon and continue on with a new map which will take in the square root and I could call this number if I want but let’s call it square root because whatever you return from the first map so this is going to be put into this parameter right here so now I’m going to take that square root and I’m going to double it so times two so now if we save that we now have the the square the number square root and then we take that square root and then we double it we multiply it by two all right so hopefully that makes sense and you can have as many of these as you want now just to kind of make it clear on what’s going on here I’m going to do I’m going to give you the long version as well so let’s say const square and double two set that to numbers dot map and what’s going on with passing in a function so I’m just going to put a long version in here and pass in here number right and then what we’re doing from this first function is returning math dot square root and passing in the number okay for each element in the array and then when we we can add the other map so here we’ll say you know I’m going to put this on a new line as well and then we’ll add our new DOT map our next dot map and in here we’re going to put a function and this is going to be the result of the last map which will be the square root so then here we’re going to return the square root multiplied by 2. okay so now if I console log square and double 2 and save we’re going to get the same result so this right here is just a shorter version of this just remember whatever you’ve returned from this map we’ll go in here if I were to have another dot map whatever I return from here we’ll go into there in fact I could say map again and pass in a function and here let’s just say square root doubled and then we’ll return let’s say I don’t know we’ll just let’s multiply that yeah we’ll just multiply that by three and Save oops this should be square root doubled okay I can’t access like this variable this right here the square root I can’t access it here what happens is whatever is returned is going to be put into here square root doubled and there we go all right so you can also chain with other methods it doesn’t just have to be map so let’s say that we want to first of all filter out and just get the even numbers then we want to double those even numbers so let’s say chaining multiple or chaining different methods so let’s say we still have we still have this numbers right here right this numbers array so that’s what I want to use so I’m going to say const and then even double so first I want to take numbers and I’m going to filter you know what let’s make this 10. so 5 6 7 8 9 10. okay so I’m going to say numbers filter and then for each number I want to remember we’re using filters so we want to say number and then we’re going to use modulus 2 equals zero so that should just filter out and give us the even number so let’s console log even double so right now it’s just going to give us 2 4 6 8 10 but now I want to add on a DOT map so I’m going to put this on a new line get rid of that semicolon and then do a DOT map so I’m chaining these these methods here I’m going to get let’s say number and it’s going to be the result of this this which is going to be an array of you know an array with the even numbers so now I’m going to take those numbers each one and multiply it by two save that now they’ve been doubled and you can do this as much as you want you can have 10 chained methods and they can all be different all right as long as it makes sense so hopefully this is giving you an idea of how these these methods work and there’s there’s a lot more we’re not going to look at all of them right now one more I do want to look at in the next video is reduce all right so now we’re going to look at a method called reduce which is used to reduce your array down to a single value and this can be a little tricky to grasp at least for me it was a little trickier than some of the others but a good use case for this and a good example is a shopping cart where you have you might have an array of products with different prices and you want to reduce that down to a total of the prices for your shopping cart that’s somewhere where you’ll see reduce a lot so if we look at this example here a very simple example there’s three arguments that I want you to understand here so basically reduce takes in a function just like the rest of them and there’s two arguments here previous value and current value so previous value is basically what’s returned from the last iteration or the last function that ran last callback this is also called the accumulator so if you hear accumulator in previous value those are both usually mean the same thing and then the current value is whatever the current element we’re on okay and then you can also pass in as an additional argument here the initial value which is whatever you want the initial previous value to be because obviously your first Loop through you’re not going to have a previous value so you can set that here and in most cases it’s going to be set to zero all right so let’s let’s look at a very similar example and then I’ll show you a like a shopping cart example so let’s say we have an array of just numbers and we’ll just use one to ten okay and then I want to get the sum of all of these numbers so I’m going to create a variable called sum and let’s use reduce on the numbers array and like I said it’s going to take in a function just like the rest of these array methods and actually Let’s do let’s do a long version of the function first just to kind of give you a better idea of what’s going on so the function will take in the either the previous value or accumulator I usually use accumulator and then the current value all right and then to set the initial value which isn’t actually required but if you want to set that you can add it after the the curly braces here and let’s say zero set to set that to zero oops and then in here what I want to do is return the accumulator so every time this runs I’m going to take the accumulator or the previous value and add it to the current value and that should in the end give us a sum of all the numbers so let’s come down here and console log sum and let’s go to our console and you see we get 55. so basically it started at zero because that’s what we set here then it went through ran a function for each element took the previous value so for instance when it was on 2 it took one and then added the current value so it added two then it the function ran again for the next element and it took 3 and added the previous item or value which is two and I kept doing that until we’re done with the array all right and then of course you can shorten it up and we could say const sum equals numbers Dot numbers dot reduce and pass in here an arrow function and you could shorten it up to like ACC is is commonly used and then c u r r c u r for current value and then we could just say we want the accumulator plus the current value and then for the initial value we’ll pass in zero and let’s just change the variable name to sum2 and we’ll console log sum2 and we should get the same thing now if I take this initial value and I set that to let’s say 10 and then I save that and run it you’ll see we get 65 and the reason for that is because now we’re starting at 10 okay before we do anything we’re starting at 10 and that’s what this accumulator is going to be on the first run through so now we’re going to get 10 more than than we normally would okay so I just want you to understand what these these arguments are now to make this even a little more clear I’m going to do this with a for Loop so we’ll say using a for Loop because there’s so many different ways to do the same thing and if you were to use a for Loop instead of reduce that’s not wrong at all it’s just a little longer so I’ll even put this into a function we’ll use a function expression so I’ll say const sum 3 and then set that to to a function so I’m going to initialize the accumulator so we’ll initialize that at zero and then we’ll do a for Loop and I’m actually going to use a 4 of since we’re going through an array so we can say const and we can call this number or we can even call it Cur like like we did above of numbers because that’s the name of the array and then all we have to do is set the accumulator equal to the accumulator Plus the current value okay now an easier way to do this or a shorter way to do this is to use the plus equals syntax we can just do that all right and then outside of the for Loop we’ll go ahead and return whatever the accumulator is and now if I come down here and I run a console log of sum 3 uh whoops this is a function I need to make sure we add the parentheses and now you can see we get 55. okay and there’s just so many ways to do this you could even do this same kind of thing within a four each so hopefully that kind of puts us into perspective a little bit now a more realistic example would to be to have a shopping cart so let’s do that I’ll say we have this cart which is an array of products we’ll say let’s give it an ID we’ll say ID and then name product one and then a price price will say 130 and then let’s say we have three products so this will be two three and product two product three and then the pricing let’s do 150 and then 175. all right so if you want to pause the video and try to get use reduced to get the total of these prices then you can do that now so we’re going to go ahead and create a variable of total and set that to cart dot reduce and we could we could either pass in a short Arrow function or we could do the long way which I’m going to do here and this is going to take in the accumulator and it’s going to take in the current value now instead of using like Cur or current value I’m just going to put in product because that’s that’s what it is right where We’re looping through these products and each value is going to be a product so that makes more sense to me and then we’re going to just return from here the accumulator plus now if I just do product right because that’s what we did up here we just plus the current value it’s not going to work here because these are objects these the the actual elements that We’re looping through and running the function on were the numbers we were adding in this case it’s a property of price so you want to make sure that here you add dot price all right and then for the initial value we’ll set that to zero and now if I go ahead and console log the total we get 455. okay if I add let’s say let’s make this 200 and save now it’s 480. so this is something that’s extremely common with things like shopping carts all right so that’s reduced now there there are other high order array methods and I want to get to those but I know that some of you are dying to just start to work with the Dom and actually put things in the browser and work with events and stuff so we’ll get to some of the other ones later when we can actually Implement Dom elements but before we do that I just want to give you a couple challenges in the next video okay so now we’re going to do a couple challenges with array methods and these aren’t too difficult if you watch the past three or four videos then you should be able to to get this at least one of them so the first challenge is to you can see we have an array of people has a first name last name email phone and age so the instruction is to take the people array and create an array called young people that stores objects with only the a name and email property of all the people that are under 25 or 25 and under and the name property should have their first and last name so basically we need to convert this into an array that has just a single name property with both their first and last name and only the people that are on over what is it no 25 and under okay and you should just have a name and email property and again the name should have both the first and last name so that’s what we want to get from this array is the the expected result so if we console log young people then we’re only going to get these three because they’re all 25 or under you can see we have a name property all right so if you want to try that out go ahead and pause the video and you can do it on your own all right so I’m going to copy this array so we can use this and then let’s come over here and let’s paste that in all right so we need to first of all I mean you can do this in different in a different order and you can use different methods I’m going to go ahead and filter out the the young people or I should say filter out the older people so that I only have young people so let’s say const young people and we’re going to set that to the people array we want to filter through that right so in filter let’s pass in a function and we’ll say for each person we want to return only if the person is less than or equal to 25 all right so we can go ahead and console log that let’s say Young people and save that and I get nothing let’s see what did I do wrong here people.filter person we’re going to return if they’re less than oh I forgot the age so I’m saying just person which is the entire object of course we want the age and if we check it out we get Jane Sarah and Jose that looks correct so Bob is 45 Jane is 25 so she’s included John is 30. he’s not included so it looks like we haven’t filtered down now we still have all the properties we want to narrow this down to only have a single name property with both first and last name and email so so what I’m going to do is is chain on a map method here so let’s say map and in here we’re going to pass in the person and remember what I’m passing in here is going to be the return from this so it’ll be the filtered persons that I’m accessing here and then I just want to basically rearrange it to just have the name and email so I could do a couple things I could do this and then and then use return return the object or since I’m just returning a straight object I could put parentheses here and use my curly braces and do it this way and say name and we’re going to set that to the person Dot first name and then I’ll just concatenate you can use template strings if you want but I’m just going to concatenate a space and then add on the person dot last name and we also want the email so we’ll set email to person Dot email so we’ll save that again and let’s see what we get so now we have an array and it only has the name and email and the name has the first and last name all right so that’s the first challenge so the Second Challenge is to add all the positive numbers in the array so here we have an array called numbers it has both positive and negative we want to be able to console log our our variable that has you know our solution and we should get 79 so 50 plus 20 plus 2 plus 7. all right so you don’t want to add the negative numbers so again if you want to pause the video and go for it then you can do that now so I’m just going to add comment here say this is challenge one and then let’s go down here and here is a challenge two so we have our numbers let’s actually just copy let’s grab this okay we’ll paste that in there all right so we want to be able to add we want to add all these numbers so let’s create a variable here called positive sum and again we’re going to be filtering out some stuff here so let’s say numbers and I’m going to go on to the next line and filter and what we want to filter let’s pass in our function and say for each number we want to let’s say we’re going to say if the number is if the number is greater than zero so that’s the truth test right if it’s if the number is greater than zero then it’s going to get put into the array now if we console log this positive sum I get 250 27 so right now we just have an array of the positive numbers now we need to get the sum of those prettier fix this for me I didn’t want it fixed but it’s all right now I’m going to come down here and I’m going to use reduce to add them together so remember reduce is going to take in the accumulator or the initial value and then the current value and then oops and then we want to run our function which is just going to take the accumulator and add on the current value and we’ll pass in zero as the initial value so now I’ll save that and there we go we get the single value of 79. all right for the next one we’re going to create so we have this this words array coder programmer developer all lowercase and now we want to create a new array called capitalized words with the words from this array but have the first letter capitalize so this is the result that we should get okay so shouldn’t be too difficult let’s go ahead and say challenge three and we want the words so let’s create that array first so the words are coder and programmer and these are all lower case and then developer okay so now I’m going to create a new variable just call it c word so capitalize words we want to set that to the original words array and we want to map through because that’s what we want to do is we want to map through and manipulate this and and create a new array with the capitalized words so this takes in a function I’ll use curly braces here and pass in word because for each word we want to then return and this is similar to a challenge we had I think in the first section where I had you uppercase the first letter of of a single word now we’re doing it in Array but what we did then was we used two uppercase now if I were to add to uppercase to the whole word then and then let’s return this I’m sorry console log this c words and save then all the letters are uppercase which we don’t want we just want the first one uppercase so there’s a few ways we can do this we could use the Char um uh method here or we could just use the index because even though it’s a string we can still use the index to get a specific character and we want to get the first character so if I save that now you’ll see that we’re just getting the first character in its uppercase now we just want to add on concatenate on the rest of the word and we can do that with slice remember if we take the word and we we use dot slice we can return a specific part of the word and this goes by index so I’m just going to put a 1 in here not a 2 a 1 and that will get basically from the one index which is the second starts at zero and it will get that over okay from there on or you could pass in a second argument to where you want to go which would be the entire length of the word so I could say word dot length as the second argument so if we save that now you’ll see we get Coda Pro grammar and developer and we have the first word uppercased all right so that’s it in the next section we’re finally going to get into working with the document object model and actually doing stuff within the body of the web page I know we’ve been doing a ton of console stuff but I think that this what we’ve been doing is really really important for you to understand before we move on to button events and doing you know moving things around in the browser or whatever I think the the fundamentals including iteration and control structures and data types that’s all really really important for you to understand all right so let’s move on to the next section all right guys so in this section we’re going to start to look at the Dom or the document object model and I’m sure that a lot of you have been waiting for this section many of you may have even started the course here I just want to mention that before you jump into the Dom you should have a good understanding of the fundamentals so things we’ve talked about like data types functions flow control loops even array methods I would suggest that you have a basic understanding of that stuff first now I’ll talk more about what the Dom is in the next video but it’s essentially an interface that allows us to interact with page elements dynamically from a language like JavaScript and in this section we’re going to look at things like the properties and methods available on the document object including methods to select elements we’re going to look at how to Traverse the Dom and navigate it so that we can change and add and remove elements from the page dynamically also change Styles and attributes so there’s a lot of different methods and functions that you’re going to learn so I would suggest following along and keeping the sandbox handy so that you can reference it at any time now after we learn how to manipulate the Dom in the next section we’re going to start to get into events so that we can have even more Dynamic functionality alright so let’s get started okay so now we’re going to jump into the document object model and we’re going to spend half the half this video in some slides and trying to give you like a visualization of the Dom and then I want to jump into some code and we’ll look at the the window object which has a child object called the document object now as far as what the Dom is it is essentially a programming interface for web or HTML elements we already know we can display the content of web pages using HTML tags with text and we can style it using CSS you guys should definitely know that at this point and the Dom is is the structure of the web page that we can interact with we can interface with using JavaScript and you can use other languages as well but for the most part you’re going to be using JavaScript and it generally includes all the HTML tags so you have access to those attributes the text between Queen tags those are called text nodes and when you visualize the Dom you usually visualize it as like a tree structure similar to what you see here on the right and what you see on the right is a tree structure of this web page here which is very simple so we just have our HTML tags head and body tags we have a div an H1 a paragraph so over here I’m going to talk about window and document in a few minutes so let’s just look at HTML now this HTML element here represents this HTML tag in our page structure okay and we will be able to access that through the document object and in that HTML tag we have two children or child tags or elements we have the head and then we have the body now in the head we have another title element and in that title element is a text node so a lot of people when they start out a lot of them think that the Dom just it just refers to the tags right the elements well it also refers to text nodes it also refers to attributes so you can see in the head tag we have a meta tag and that has a character set a Char set attribute on it which we can easily access and and do things to add to remove or whatever on the bot in the body we have a div and that div has an attribute on it of ID and then in that in the div with the ID of main we have an H1 that H1 has both an attribute has a class on it and it has a text node in it all right and then the paragraph has a text node in it as well so when you look at HTML structure you should be able to kind of picture this type of thing in your head when you’re dealing with the Dom all right now I want to just jump into vs code now and just kind of look at some of this real quick so in the console I’ve already showed you this if we type in window it’s going to show us that the window object which is the the topmost or the global object in the browser that has a ton of stuff on it including the document object and we can of course access that from within our code as well all right that’s going to give us the same thing and in that window object is the document object so right here and that has a bunch of properties and a bunch of helpful methods that we can use as well so we could do a console log window dot document and I’m just going to comment this out so now you’ll see document and since we did a console log to the document it’s going to just show us the element if we want to see like the properties and methods and stuff then we can do a console.dir and now if we take a look you can see all this stuff here and I’m going to go over a lot of the different properties in the next video now I’m just going to show you a couple things and we’re going to touch on all this stuff much more later on but let’s just do a console log here and we’ll say document now we don’t have to prefix it with window you can because it is on the window object but since window is the top level object you don’t need to prefix this stuff with window in fact you’ll very rarely see window dot document so as you can see over here there’s a body property here and that that references the body element so if I say document.body and save that it’s going to show me the actual element okay so you see the body element you can see the H1 and the script tag some of this stuff is injected by live server but we can see everything in the body right and then there’s properties we can use on this like let’s say we just want the HTML in the body we could use inner HTML save that and now you can see we have an H1 and our script tag and if we look at the HTML page that’s exactly what’s there if we wanted to get let’s say just the text we could use in our text save that and we just get Dom intro all right if I were to add something else in here and just put a paragraph with hello just the text is going to show here if I go back to using in our HTML it’s going to show the paragraph as well all right now typically you don’t access elements with direct properties like this because there’s methods like like get element by D and query selector that I’m going to show you very soon that helps you target what you want much more easily I but I do want to just show you some of the I guess the the more difficult ways of doing it first so let’s say we want to get all the links on a page all right and I shouldn’t say more difficult but but using properties rather than using the the methods so let’s create a link here and I’ll just have it go to my site travestymedia.com and say Traverse media for the text all right and then let’s say I wanted to access all the links I could say console log and then document and if we look over here in the properties there should be a link so you can see there’s images to access all the images and then you also have links now since there’s more than one link on the page what this gives us is something called an HTML collection which is very similar to an array you can access each link by index just like you could in Array so let’s say document.links and we’ll console log that in fact let’s comment out this stuff here so as you can see I get an HTML collection and there’s a single Link in there it has an index of zero so if I want to access that I can simply put brackets just like I would with an array and then put the zero and there it shows me the link okay and if there were if there was another link I could use one as the index there’s not so it’s going to just be undefined now this for instance this document.body this is not read only I can change that from here I could say document.body equals or actually let’s say document.body dot in our HTML equals and then we’ll just put an H1 in here and we’ll say hello world all right so if I go ahead and save that it’s going to replace everything that’s in the body with just this H1 even if we had you know a ton of content on the page if I set the body in our HTML to this H1 it just replaces it now I’m going to show you all kinds of methods to insert things where you want but this is just saying well I just want the entire page to show this H1 which is something you’re not going to do now there’s also methods I’m just going to comment that out there’s also methods on the document on the document object so one of them which you don’t see very much is right so right will actually take whatever you put in here and write it to the browser so if I say hello from JS and I save it gets added now the reason you don’t see this used very much is because there’s no targeting it just basically puts it at the whatever at the end of the file and it’s not it’s just not very helpful but this is a method right it’s a function now there there’s also methods to select certain elements in the Dom and those are very very helpful and we’ll be going over those you know in depth but just to give you an idea let’s go to the HTML and let’s wrap I’m going to wrap all this the H1 and the link with an ID of main okay so I have this div with the ID of Main and I’m going to move the H1 and the link inside of that and let’s say I want to select that Main that main ID so I’m going to just console.log document Dot and then the method I want to use is get element by ID okay so we’ll say get element by D and in here is going to be the ID I want to grab which is main if I save that and you see it grabs that div with the ID of main now I can do what I want with that I could say document Dot get element by D main I could also put this into a variable so for instance const main equals that and then I could say main dot inner HTML equals and then we’ll put an H1 and we’ll say hello from Main okay save that and it’s going to replace everything within that that div with the ID of main with this H1 okay just like I replaced it up here I replace the body this is just replacing this specific element okay and there’s there’s even better selectors like query selector where you can select anything you want so for example if I wanted to select just the H1 I could say document dot query and don’t worry we’re going to go over this much much more in depth so I could say query selector uh and let’s say I want the ID of main so I would use the number sign here because you can choose classes or or just straight elements whatever and then I want the H1 so it’s basically like if you were styling this with CSS you can put any selector in here and let’s say I want to take the inner we’ll do the inner text of that H1 and let’s set it to hello save that and now just the H1 gets changed so this is just a very very high level example of some of the things that we can do all right so in the next video I want to look more at some of the properties on this document object all right so in the last video we looked at the document object model and what that is we looked at the actual document object that we have access to within the window object and some of its properties and some of the methods we can use so I want to take a look at some more properties that’s on that object that you have accessible to you that you can you can access you can also use to overwrite and you know add things through JavaScript so a lot of these you’re not really going to use because instead of selecting them the elements with these properties you’re going to use methods like get element by D and query selector but I do want you to at least know that they exist all right so you’ll notice that we actually have some life in the browser finally so this is a UI for the shopping list application that we’re going to build in a little bit and it’s not functioning you’ll see I cannot add anything I can’t delete anything that’s because there’s no JavaScript at all it’s just HTML and CSS and you’ll have this in the sandbox you’ll also have it in you should have it in this the current video module that you’re watching all right and just to take a quick look at the HTML we’re just bringing in font awesome which is a library to use icons like this right here I believe is actually no that’s not how to font awesome the think just the delete buttons are here but yeah so we’re just bringing that in the bringing the CDN and then we’re linking in our style sheet so this is just custom CSS so very simple we’re not using like Tailwind or any CSS framework and then we have our header our container with our header just has this little image and and heading and then the form here with the input to add an item the button to add an item then we have a filter input as well so we’ll be able to filter these items down then we have the unordered list which is the item list and then we have the clear all button so that’s pretty much it and then we’re linking in a script JS which is completely empty That’s why nothing works okay and and a little later on we’ll create this whole application and get it functioning but I want to use it just as an example UI for the next few videos so that I can show you how to manipulate the Dom and you know access certain elements change things and so on so again I want to look at some of the properties on the document object so I’m going to just initialize a variable here called output so that I can console logs different things and let’s open up our console over here so the first property I’m going to show you is actually deprecated but I still think you should know it and that’s document.all so I want to set output to that so we can log it now you’ll see it actually has a strike through in vs code because it says it is deprecated but if we look over here what it gives us is an HTML all collection so this is similar to an array and you can see it has brackets and it’s basically an array or a collection of all of the different parts of the this page the Dom for this page so HTML tags a script tag head tag everything in here the form the inputs everything is going to be in this HTML all collection and we can even access axis Elements by index so if I do 10 that gives us the body if I do 11 that gives us the container so you can access items or elements like this but this is not like the way you want to do it this is not very convenient and this is the reason I wanted to to teach you like what arrays are and how to use them and stuff because if if you didn’t know what an array is you wouldn’t understand an index or what this is right so it’s important to learn the basics now you can also use like the length property just like you can on a regular array so you can see there’s 38 items in there but it is deprecated I wouldn’t suggest using it but I want you to know what it is just in case you run into it now we also have if you want to get everything that’s in the HTML element or tag you can use document element and that will just give us the HTML tag and then everything in it head body and so on then we can also access just the head or just the body so if we say document dot head and we save that that gives us the head we can do the body I showed you that in the last video as well now if you want to get the children in the head or the body so if you want to get the children in a collection you can it’s actually do that so you can just do dot children and now what we have here is a collection of everything that’s in the head the script tag meta tag link tag we can do the same with the body so if I do that that gives us everything that’s in directly in the body that’s why there’s only a single div here because if we look there’s a this div with the class of container everything else all the other HTML is inside of that so it’s only going to give you the the parent I should say the direct child of the body if I were to put an H1 in here and save that that H1 will get added to this collection because it’s at the top level right where container is so that is dot children which you can use on the header body now some other properties we can get are the the doctype so let’s say output equals document dot doctype if for some reason you need to get that we also have the domain domain I believe is deprecated as well but as you can see we can get the domain which for me is my Local Host we can get the URL the full URL as well so that’s going to be the domain plus any page that we’re on we can get the character set so character set which is utf-8 so just some things that you can get for your application if you need them the content type so we can say document dot content type which is going to be Text slash HTML now I showed you that we could get links as an HTML collection in the last video and I’ll go over that again in a minute but we can also do that with forms so I could say document dot forms and save that you see that gives me an HTML collection of the forms if I want to access a specific form I could use an index because again an HTML collection it works like an array as far as indexes go so you’ll see I get my my item form here now I can also get specific attributes on elements as well so let’s say I want to get the ID I can say dot ID and you’ll see I get item form okay I could get the method of the form so we can say method save that and it’s going to be get because we don’t have a method described here but a form is always going to it’s always it’s always going to be get as the method unless you set it specifically like if I set it to post so if I say method post and save then it’s going to be post and we’ll get into what that means later on there’s also no action which is where it submits to if there isn’t an action it’s going to submit to that page but I could get the action with DOT action and it should just be the same page so the page that I’m on now if I wanted to change the ID of the form I could do that by saying document dot forms and grab the first form in the document and take the ID and set it to let’s say new Dash ID right so if I save that now and I come over let’s go to the elements Tab and take a look at the form I’m going to close that up and you’ll see form has an ID of new ID so I set that from my JavaScript all right um I’m just going to comment that out though now I could do the same thing with links as I showed you in the last video so I could say document dot links which do I even have any links in here let’s go back to the console here yeah so it’s just an empty collection because I don’t have any links if I did if I put like let’s say https google.com and I’m going to get rid of this after but just to show you if I have a link then that’s going to get added to the collection and then I can access the first and only link with the index of zero and if I want to access just the just the link the href I can use the href property so I’ll say dot href all right if I wanted to set an ID onto this link I could say dot ID and set that to let’s say Google Dash link and if we go back into elements and we look at the link which is let’s see where is it um I think it’s in here yeah so ID Google link I could even change the href so let’s copy that down and set that to https facebook.com and save and now if we look again at the link right here you’ll see the ahref is now Facebook okay and then for classes like um for those CSS classes you could change now you can’t do this you can’t say dot class but you can do class name and I’ll set it to I don’t know Google class and save and now you’ll see we have a class of Google class and then if we want to access all of the classes we can get a collection of those with class list so let’s say dot class list and I’m not going to set this I just want to log it so we’ll save that and go to our console and you’ll see that now we have it’s actually called a Dom token list so any classes on that element will be in this list all right now we can do the same with Let’s see we did forms links we can also do images so let’s say output equals document dot images which will give us an HTML collection if I can spell this right document so that gives us an HTML collection of images let’s get the first image so this index of zero and that’s going to be this right here this note PNG which is the first and and only image if I wanted to get the source of that image we could use the source property all right so I just want you guys to know these these different properties that we can use to access these elements now the this is not the best way to do this if you want to access a form if you want to select it for something you don’t really want to do this or this for links or this for images but I want you to know that this does exist because you might run into it and there might be some reason why you do have to use it now I’m just going to get rid of this Google link it’s going to throw an error because it’s looking for links and I don’t have any so I’m just going to comment this block of code out and then the last thing I want to mention is that what we’re getting back when we do this document forms document images is an HTML collection which is array like we can access the specific uh forms for instance using an index just like an array but if we try to use a for each on it it’s not going to work so let’s actually try that out if we say document let’s use form so we’ll say document.forms.4h you guys should know this we went over this in the last section and this takes in a function we’ll say for each form then we just want to console.log the form right now if I save that it’s going to say that for each or forms.4h is not a function okay because 4H is not a function for what we have here which is an HTML collection okay later on when we use Query selector that actually gives us something called the node list which is different than an HTML collection and we can use for each on that but for an HTML collection if you do want to use four each you would have to first convert it to an array and you can do that with the array from method that we looked at a while back so I could say const forms right create a variable called forms and set it to array capital a DOT from and then pass in our document dot forms HTML collection and then I should be able to take that forms array and then Loop through it and now you can see it’s outputting this uh this form here okay because we only have one form if we had more it would show them here because it’s looping through and logging it okay so I just want you to understand an HTML collection is array like but it’s not actually an array and this is how you can turn it into one now in the next video we’re going to start to look at methods that we can use to to more easily select elements from the Dom all right guys so in the last video we looked at many of the properties available on the document object including properties that allowed us to select elements from the Dom in the form of HTML collections now in this video we’re going to look at a much more common and practical way to select elements and the methods that we’re going to use here are to select single elements on the page so if you want to get let’s say all of the paragraphs on the page you wouldn’t use these methods we’re going to look at those in the next video methods to select multiple elements for this is like if I wanted to select this particular H1 or this particular input then we would use these methods all right so the first one has been around for a while and it’s going to be document.getelement by ID so basically it does just that it’ll allow us to get any element in the Dom by its ID so if we look at let’s see if we look at the elements tab here and in the dev tools you’ll see that this H1 has an ID of app title so I want to get that let’s go ahead and we’ll do a console log of it first so document dot get element by ID and it has an ID of app dash title so if I were to log that in the console we’re going to see that H1 now there’s going to be cases where you want to get a specific attribute so what we could do is there are properties available such as ID and there is an ID on this element so I could just add on dot ID now that doesn’t work for every single attribute for instance if I do dot class I get undefined and I know there isn’t actually a class on here but I’ll show you real quick if I were to add a class onto this H1 of say hello if I do that we still get undefined because class is not a property now there is a class name property and you’ll see that does get it but there’s no that’s not always going to be the case get rid of that so what you can do is use a method called get attribute so I’m going to copy this down and instead of this dot class name I’m going to say dot get attribute and that’s a method so it takes parentheses and then we can pass in whatever attribute we want I’ll pass in ID and you’ll see now we get app title now there’s going to be cases where you want to set attributes not just get them so there’s a few ways to do that so one is to grab the element so let’s say app dash title and let’s say I wanted to change the ID I could say dot ID and set that to let’s say new Dash ID and if we look at the element now it has an ID of new ID now if I keep this here and then I try to select by ID and I use app title again it’s not going to work because that’s been changed so let’s change this to something else we’ll add a title attribute and we’ll just say shopping list and a title will typically you know if you hover over this it’ll whatever the title is will show all right now like I said there’s not always a property for that that we can use so there’s also a set attribute method so let’s copy this down and what we’ll do is get rid of this and we just want to do dot set attribute and that’s going to take in two things the first is going to be the attribute you want to set let’s just use class and then what you want to set it to so I’ll say title and if we look here you see now class is equal to title I could have said dot class name equals title so there’s many ways to do the same thing but I just want to show you that there’s both a get attribute and set attribute and we’ll talk more about this later as well now there’s going to be times where you don’t want to type all this out like if you have to use this selector more than once you might want to put it into a variable so we can do that by just setting a variable and then setting this to get element by D and app dash title so now if I were to console log title then that’s going to give us the element now I know that this video is showing you these different selectors and we’ve only looked at get element by D we’re going to look at query selector next but I want to show you some of the things that we can do when we bring these in when we when we grab an element from the Dom all right and and we’ll go into some of this stuff more in depth later on but one of the things you’ll do is either you either want to get or change or add the content that’s within that element right so what we could do is say well it’s console log first title which is our element our title element and we could do text content which is a property that will get the content inside of it in this case you can see shopping list okay now we can also change it as well by saying title dot text content and setting that to something else let’s just say hello world save that now you see we’ve changed change that element’s text there also is intertext so if I say inner text like that and we’ll just set it to hello again that’ll basically do the same thing there are some differences between these two but I’m not going to get into that right now you’ll most commonly see in our text at least in my experience now if you want to use HTML tags then there’s a property called inner HTML so you’ll use this a lot with vanilla JavaScript but with this I could set it to let’s add some strong tags and we’ll just set it back to shopping list so let’s say shopping list let’s close our strong tag and save that and now you can see now it’s strong or bold so another thing we can do is change Styles so we can actually edit our CSS from here so for example if I say title Dot and then we use style and then whatever CSS property we want so for instance color I’m going to set that to red and you’ll see I can change that color to Red now it’s important to know that if you’re if your style has if your property has two words like let’s say background color in CSS you would do this right bat Dash color background Dash color you can’t have a hyphen here so in JavaScript what you do is just use camel case like that and then let’s just set that to we’ll say black okay and then maybe you want to add some padding so we could change the property here to padding and set that to let’s say 10 pixels right and then we’ll just do a border radius it’s a border radius so it’s two words so it’s camel case now you might be saying why the hell would I want to use JavaScript to edit Styles well you wouldn’t do it like this just to edit a static page styles on a static page when you want to have your your interface be dynamic that’s when you you do this type of thing so for example if you want to have a pop-up if I were to hit this button and have something pop on the screen a modal you would be changing your yours or adding CSS to your JavaScript okay or you would just change classes you would change a class to like show or hidden or whatever and we’ll get into that later but I just want to show you now that you can select elements from the Dom and then you can change things or add or remove whatever you want okay so you have full control of your interface through JavaScript and the Dom so now we’re going to move on to the other selector that you’ll use for for single elements and that is document Dot query selector now this was a game changer when it came out before that if you’re using vanilla JavaScript we had to use get element by D so whatever you selected you had to have an ID on uh and in some cases you didn’t have full control of the HTML so that’s where jQuery came in and gave us a big Advantage because we could select anything we could just select an H1 with no class or attribute we could select by class we could select by anything at all so that’s really what query selector gives us and this came along with the es6 or es2015 update and kind of put jQuery out of business as as like a Dom manipulator so let’s start off by just we’ll do a console log here and let’s say document Dot and then query selector there’s also query selector all which is for multiple elements and we’ll get into that next in the next video but if I if I want to select just by the selector I can do that so H1 and you’ll see it’s showing our H1 along with all the styling and all the stuff we did up here to it now remember this only selects single elements that’s kind of the difference between jQuery and this if I did this with jQuery it would select I believe it would select all H1s I haven’t used it in so long but I believe it would select all of them in this case it’s going to select only the first one if there are multiple on the page all right but usually you’re going to use this to select like a class or something like that something that you know there’s only one of otherwise you’ll use Query selector all so another thing we could select by is ID so we could say app dash title okay so that’s going to log the same thing the H1 with that that ID we can select by class so if I say dot container and we select that you can see that we get the container and you can do all the same stuff with Doc query selector right you can change Styles content and all that we could even do it by attributes so for instance if we want to get the input that has a type of text we could say input and then in Brackets here I could say type equals text actually that takes takes quotes I believe okay and if I go ahead and log that you can see now it’s it’s grabbing this input here now we can even use pseudo selectors so basically anything you can use within CSS so let’s get rid of this and instead I’m going to say an A List item if I do this it’ll just give me the first list item by default let’s say I want the second list item so I could say Li and I could use the pseudo selector of nth Dash child and pass in here two so that should give me the second list item which is orange juice and let’s actually we’ll do the inner text save that and there we go orange juice so you can select and you can Target anything on the page you want so let’s do this let’s take the document query selector and the inner text and let’s put that into a variable so we’ll say const and I’ll call it second item and we’ll set it to that okay so that’ll give us the inner text actually you know what let’s not do the inner text because I just want the element and then let’s set the inner text so we’ll say second item and then dot enter text and let’s set that to let’s say apple juice if I save now we get apple juice okay if I wanted to change the color of it then I could take the second item and change the color I’m sorry we need style so style Dot color and set that to red all right and I would encourage you to maybe you know after this video try and change some things around with what you’ve learned try to change this this interface up maybe change the color of the button change the text of the button things like that now another thing that I want to mention is that you can use you can use these use these methods on other elements other than the document so for example let’s select the entire UL so we’ll say list and then we’ll set this to let’s say document dot query selector and we’re going to select the unordered list okay which is just this right here right apples apple juice Oreos Etc so that gives us the the entire UL if I console log list it gives us the UL now if I want to select something in that list like say the first item we can use Query selector on list okay it doesn’t have to be on the the document so let’s take list and then let’s say query selector and let’s say we want to get we’ll just get the first list item and yeah we’ll just do that and then let’s actually put that into a variable we’ll just call it uh we’ll call it first item so first item equals that and then we’ll take first item and let’s change the we’ll just change the color we’ll say dot style dot color and set that to Blue save and ioc apples is now blue so you can use Query selector on any element it doesn’t have to be just on the document all right now in the next video like I said we’re going to get into selecting multiple items all right so in the last video we looked at get element by D and we looked at query selector which are the two methods you can use to select single elements now if you want to select multiple elements like let’s say all of these list items then there’s some other methods you can use now query selector all is the method that you’ll use probably a hundred percent of the time there’s some older ones like get Elements by class name and get Elements by tag name which I will show you just so you know but you’re probably just going to use Query selector all so you can get by just using this and query selector for multiple elements now as far as what this gives us let’s go ahead and I’m just gonna I’m gonna create a variable here called list items and what I want to put in here is all of these these Li tags all of these list items if I go to my elements tab here and click on that you’ll see that we have these these Li tags and they have a class of item I could use that as well for my selector but let’s say we want this to equal document dot query selector all and I can put Li in here I could also like I said I could do class item and that will select all of those let’s leave it at that because if you were to add other allies on the page somewhere else those would also get included if you just use Li now if I console log list items I just want to show you what that gives us so let’s go to our console and what what it gives us is a node list and a node list is an array-like structure much like an HTML collection which we saw in the past in fact the older methods I’m going to show you do return an HTML collection as opposed to a node list now there are some differences one key difference is you can use high order array methods on a node list you can’t do it with an HTML collection with an HTML collection you would have to first convert it to an array and I’ll show you a for each Loop in a minute but I want to show you you can also get if you want an individual item just like an array you can use the bracket syntax if I put a 1 in here that gives me the the second element let’s say I just want the text I could do let’s say inner tab okay and that gives me orange juice because it’s zero one two three and I’m getting the one the index of one getting the inner text you can access individual elements like that like an array now if I were to let’s say I want to make all the the I want to make the color of these red so I couldn’t just do list items.style dot color and set that to red if I try that that’s not going to work because I’m trying to run I’m trying to access Style on a node list okay style is is for a specific element now I could do this I could say one and change that’ll change just that but what I would do if I wanted to change all of them is is a for each Loop right so I could say list items dot for each and in here we’ll say for each item and then we’ll take the that specific item and let’s take the style set the color to Red save that and now they’re all red okay now this is different from jQuery for those of you that that have worked with jQuery because with jQuery you could in fact take the you know list items variable and do dot style color and they would all turn red but it’s a little different with vanilla JavaScript and you can do whatever you want in here like we could say if let’s say if item and remember we can access the index so I could actually do this because we already know how four each works we can pass in an index and we’ll say if the index is equal to one then let’s take the item and let’s remove it so we’ll say dot remove and we’ll get into methods like this later but now you can see that that has been removed now let’s say we wanted to change the the text of the first one from apples to oranges so we could do if and then say if the index is equal to zero then let’s take this particular item and change the inner text we’ll change it to oranges save that now notice the text does change but the delete button is also gone whenever you’re working with elements you have to know exactly what you’re working with if we look at a list item here it doesn’t only include the text it also includes a delete button so you have to take that into an account into account so what we could do is just take everything that’s in the list item and copy it and then here this there is HTML in this so we would say enter HTML and then I’ll use a template string just so it’s easier so use some backticks here and paste this in and then change apples two oranges save and now we have oranges and the delete button is also there so you see a lot of stuff like this template strings um within your in vanilla JavaScript all right now I want to show you some of the other methods that we can use that you probably won’t but I do just want to show them to you so I’m going to comment this out just so we have our original our original list back and then let’s say we want to select all these with the get Elements by class name so I’m going to say cons list items we’ll call it list items two and say document Dot and then it’s get Elements by class name okay and then we know that they all have a class of item and this is kind of restrictive because you can only do classes and you don’t want the dot actually because it’s always going to be a class just like with get element by D you don’t put the the number sign now if I console log list items two we get an HTML collection as opposed to a node list okay we can still access individual items like like we would with an array like if I put a 2 here and save actually let’s do two and then Dot in our text and we get Oreos okay so you can use you can pass in an index like this but if I were to do a four each so let’s say list items two dot four each say for each item then we’re going to just let’s just do a console log of that item and the enter text save that and it says for each is not a function because it’s not a function for this list items two which is an array I’m sorry an HTML collection now what we could do is use array Dot from to convert it to an array so I could say const list items let’s just call it list items array and then set it to array Dot from and then pass in our list items two which is an HTML collection and then if we run the four each on list items array then we’re going to see that that works all right so just keep that in mind if you have an HTML collection and you want to use for each or any other method you want to First convert it to an array now the um and then the last one I want to show you is similar to this but it’s called get Elements by tag name so I’ll call this one list item three and let’s say get Elements by tag name and then you would put in the tag like Li list item so if I console log list items three again it’s an HTML collection so if you wanted to use a four each you would have to first turn it into an array but you can access specific things like let’s say we wanted the first item that gives us the first item if we want to get the inner text we get apples okay and I’m not going to do much more with these because I’m pretty sure that this is the only time we’re using these in the course okay you want to stick with query selector all for most cases so you can get by with just using query selector and query selector all all right so in the last few videos we looked at how to select elements from the Dom and do whatever we want with them now in this video I want to start to look at the relationships between element nodes okay everything in the Dom is a node and there’s other types of nodes like text node comments nodes we’re going to talk about those in the next video because there’s certain properties if you want to work with those types of nodes in this video we’re specifically going to look at element nodes okay so any HTML tag on the page is an element and I also want you to just be familiar with relationships which you should you should be if you know HTML if we look at this basically it’s pretty simple to tell that this div is a parent of these three divs inside of it and I even gave them the class names of parent and child and then any div that is on the same level such as these three children are siblings right so these are sibling nodes or sibling elements and I didn’t want to use the the shopping list UI just because I want something very very simple so that I can explain these methods and and show you how to use them I’m sorry not methods these are actually properties and the properties I’m talking about are these ones here okay so we’re going to look at all these so we have our parent element which we just saw it was a div with the class of parent and then we have our three child elements and there’s different properties for us to basically Traverse the Dom move up and down so we have we have a property called parent element which does just that we have a first element child a last element child next element sibling previous element sibling and then we also have a property of children which gives us I believe it’s a node list of all the children alright so let’s start to look at this in our code so I’m going to just close that up and I have this open I’m going to open up my script.js here which is completely empty and we’re going to start to look at some of these so what we’re doing here is still just selecting stuff from the Dom but in a way where we do we’re not directly selecting it we’re using elements we’ve already selected we’re using properties on those to kind of navigate and Traverse to the children the parent the siblings Etc so the first thing I want to show you is how we can get child elements from the parent so let’s create a variable here I guess we’ll we can call it parent and let’s say document Dot and then query selector and I want to get the div with the class of parent okay so that gives me if I console log parent gives me that div all right now I just want to create an output variable so let’s say output just because I’m going to be console logging quite a few things so we can just then set it to Output all right and what I want to show you is how to get the the children property so if we look at this diagram here there’s this children property that gives us an HTML collection of all the children so let’s say output and set that to parent and then children now this is a property or an attribute it’s not a method if I put parentheses here it’s going to tell me that children is not a function because it’s not it’s a property and what it gives me is an HTML collection which is an array-like structure of all the divs in here all the child divs now since this is an array-like structure I can access each individual element here with an index so I put if I put a 1 in here I’m going to get child 2 right because it’s zero base so child two would be the one index and I just want to show you if I instead of logging this if I do a console dir it’ll show me like all the properties and methods that I can use on this so we can access like the ID with DOT ID the class list um even the children of this we can access just all this stuff here so just to give you kind of an example let’s put this back to console.log and let’s uh let’s get the inner text save that we get child two right if I do let’s say class name I get child because remember it has a class of child we could even do like the node name which will give us a div because that’s what this is if I take the second one here and change it to An Li then node name is going to be Li all right so we can treat it just like we could treat a directly selected element now I can change things as well so if I want to grab let’s say parent Dot children and then one and let’s set um we’ll say text not text inner text or text content whichever one let’s set that to I’ll just uh we’ll say child and then we’ll spell out the word two so that should replace the child number two and I could also add styles to this so I could say one dot style Dot color and set that to Red so we could do that as well now in addition to the children HTML collection there’s also two other properties that we can use on our parent and that is first element child and last element child now there is just a first child that’s not what you want because that isn’t just element nodes that’s other nodes as well which I’ll talk about in the next video what we want to use is first element child okay so and it’s a property it’s not a method so don’t put uh parentheses and let’s just change this let’s say dot text our inner text and we’ll set that to child one save that and you’ll see it change the first one here and again just to look just to reference this diagram from the parent we called this right here first element child and as you can see there’s also a last element child so if we come back here let’s copy this down let’s change this one to child three and change the property from first element child to last element child and now you can see that that’s been changed so now what I want to show you is how we can get parent elements so get parent elements from a child because if we look at the diagram again it goes the other way as well these child has they have a property of parent element okay and we can also access siblings as well which I’ll get to so let’s go ahead and select from the Dom let’s select it we’ll say child and set that to document Dot and let’s use Query selector and we’re just going to select the first child we’re not going to use Query selector all because I don’t want that I just want to get one of these elements and show you how we can access the parent from it okay so we have the child now let’s set output because I want to show you how we can access let’s say child and then we can use the parent element property so if I save that we output now you’ll see we’re outputting the parent by using the child by using this property on the child now let’s say we wanted to add a border around the parent div from the child so I could say parent element and let’s set dot style dot border and we’ll set that to let’s say one pixel solid and we’ll do Triple C for the color and then let’s say we wanted to add some padding so we’ll say 10 pixels and change this padding and save and now you can see there’s a border around the div with the class of parent and I didn’t apply that to parent directly that I selected I selected a child but then I used the parent element property to access and change the style of the parent so now let’s look at sibling elements so sibling elements oops put two L’s in there all right so let’s grab let’s grab the second item right so I’m going to create a variable called second item and we’re going to use document Dot query selector and remember we can use we can put any selector we want in here so I’m going to say I want the class of child now remember there’s three of those I want the second one so I’m going to use this the CSS pseudo selector of nth Dash child and pass in a 2 here so that will give me the second item all right and just to show you let’s do output set that to second item and save that and you’ll see that now this gives us child two this one right here now if I want to access the next sibling from second item which would be the third one that I could use next sibling right so let’s set output equal to second item and then we’re going to do dot next I’m sorry it’s not next sibling that will do the next node no matter what it is next element sibling will give you the next element sibling so let’s do that now you see it’s we get child three and if I wanted to let’s see let’s just grab this and copy it and we could do something to this like I don’t know let’s set we’ll say style dot color and we’ll set that to Green okay so what I’ve done here is I’ve selected the second item directly using query selector and then I use the next element sibling property to get the next sibling and then I turned it green now we also have previous elements sibling so let’s copy this down and this one let’s say orange and I’m going to change next element sibling to previous element sibling and now you’ll see that first one is now orange because that’s the previous to the second item okay so hopefully this just gives you an idea of how to kind of how to navigate around if you select an item but then you want to get it sibling or its parent or its child there’s different ways to do that now as I said there’s other types of elements I’m sorry other types of nodes other than elements so we’re going to start to look at that in the next video okay now as I mentioned in the last video when it comes to Dom nodes there’s different types and in the last video we strictly worked with element nodes and that’s the most common type of node basically an HTML tag now if we look at this chart here this is actually from w3schools and you can see these are the different types of node types there’s 12 of them now a lot of these you’re not even going to need to know or work with but as you can see the first one here is an element node it represents an element and that’s what we were looking at in the last video and there’s specific properties that we can use that pertain to element nodes now some other types of nodes are attributes okay an attribute like an ID or whatever it might be an attribute on an HTML tag those are attribute nodes we also have text nodes which represent textual content okay so any text written within some HTML tags would be a text node we also have this C data section which represents a c data section in a document which is text that will not be parched by a parser we also have entities and entity references this stuff isn’t really that important to you right now comments so if you have a comment that is also a separate type of node so what I want to do is look at some of these other methods that are available to use with with not just element nodes but other types of nodes as well and this looks pretty similar to what we already saw but these are actually different methods okay same structure we have a parent with three children but we have for instance first child instead of first element child last child instead of last element child parent node instead of parent element node next sibling in previous sibling instead of next element in previous element sibling and there’s also a property it’s kind of cut off here but it’s child nodes instead of children okay so just remember that this works with all nodes while this works with just element nodes which is usually what you’re going to be working with what I’m going to show you here in this video probably you’re probably not going to use too much but I do want to mention it I want this to be a front to back course all right so the only difference between this HTML and the last is I simply have a comment here that says children because I want to show you that a comment is looked at as a specific type of node all right so let’s jump into the JavaScript here and I think the first thing we’ll do is look at the child nodes property just like we had a children property but we want to do that on the parent so let’s go ahead and again create parent document we’re going to query selector and we want to select the class of parent okay and then I’m also going to create a variable called output and then oops and then we’re going to console log that output and let’s just open up our console here okay so right now that’s undefined but I’m going to set output equal to and then take that parent element that we selected and look at not children but child nodes and it’s a property not a method so no parentheses and now you’ll see what we get back is not an HTML collection but a node list and that node list includes all different types of nodes so we have a text node a comment so what I want to do is is go back here and kind of go through and show you what what this pertains to and this goes from the where the parent class as it did with the parent class starts which is right here to where it ends which is right here so all of these nodes are in between that and you might be saying well how I mean where the first one is a text node where is this I don’t see any text well white space actually counts as text so this comment goes on to the next line so this right here is actually that first text node okay if I were to I mean I’m going to have to disable format on Save so if I search for format yeah right here format on Save otherwise it’ll knock it on to the next line but if I take this comment and I put this right here and then get rid of that white space see how right now this is 0 to 8 which is a length of nine because the text node if I save this and look at it now there’s no more text node and it’s a length of eight zero to seven so that text node is gone because that white space is gone if I put that back and I save it then that text node is there again so that’s the first thing next is the comment okay comments of their own nodes if I get rid of this and save then you can see that that com not only is the comment node gone but also is the white space after it okay this right here if I put that back it’s going to go back to a length of 9 and the comment and the white space after it okay this right here then we have our element node which is a div with a child okay div with the class of child then we have our white space which is the text then another div element then another white space with text then another div and then another white space okay so that’s what this is so as you can see this navigating this instead of just the elements like in the last video is much more difficult so you probably won’t be doing this that much unless you specifically need to access text nodes all right let me just put format on Save back on okay so now what I want to look at is we’ll we’ll stick with child nodes just just for a bit just to kind of see how we what we can access here so if I say output and set that to parent dot child nodes and we grab zero that’s going to be that the white space the text node as you can see gives us this text node and we can get all this this stuff from it right like we can get um let’s say text content not with a zero and that just it’s just nothing right if we look at let’s say node name that’s going to be text right so we have we have access to all these properties let’s look at a different one so we’ll copy this down and let’s do three I believe was the first element so if we do three yeah three node name is div if we just look at let’s say the text content we get child one if we look at the we know that that’s the element so we can get the inner HTML which is still child one because there’s no HTML in it if we want the HTML that surrounds it we can use out our HTML which is one t so now it gives us the div with the class of child and child one all right so we’re essentially doing the same thing we just have access to all of the nodes and not just element nodes if I wanted to change let’s say um let’s say dot in our text and I believe this should be the first one so let’s change it to child one spelled out yep so if I if it’s just it’s more difficult to figure out what you need to access because there’s so many of these other types of nodes um what else we could change we could change the color so we could do I think six would be the second one so six dot style dot color equals red or maybe not forget which one was it seven or was it five yeah it was five so that’s the second element all right now in addition to child nodes we also have first child and last child so let’s say output equals parent DOT first child just like we had remember we had first element child but that’s going to give us the text node the white space right if I were to I’m not going to turn off my format on Save again but if I were to put this up here uh not that if I were to put this up here that would get rid of the text node and the comment would be the first one but if I save I have format on save so it’s not going to allow me to do that all right we also have last child which is also a text node um what else let’s see and I could since it’s a text note I could say parent dot last child Dot text content and set that to hello so that’ll replace the text node which was originally white space with hello so now I want to look at parent nodes or getting parent nodes from the child right so what we’ll do is create just like we did in the last video create a child we’ll use document.query selector and we want to select a class of child okay so what we’re doing is selecting this right here now to get its parent node we can use the parent node property so let’s say output equals child dot parent node and that’s going to be the the actual div all right and if we look back at this chart what we’re doing is accessing this parent node now it’s going to be the same as parent element right even though we have these other types of node like text and comment the parent is still going to be the same so if we were to for instance do here parent element and I say we’re going to get the same exact thing so you could use either in in this case and if I wanted to say like child Dot parent node dot style Dot uh back we’ll say background color and set that to hex value actually let’s do let’s do something a little darker yeah so we could do that all right so that’s pretty much it as far as accessing the parent because there’s only one parent node right when it comes to children you have multiple children nodes now as far as siblings siblings I’m gonna once again get the second item so I’m going to do that with document Dot query selector and we’re going to get the class child but we want to get the nth so nth child two that’ll give us the second one so just a make sure that’s correct let’s set output equal to second item okay so we have the second item now if we were to get the oops Let’s uh let’s bring this up here so if we were to get the um next sibling right not next element sibling but next sibling it’s a text node okay because of that white space because we’re right here right now and the next node not the next element would be this but the next node would be the white space here if I were to take this and and close that white space then yes the next one would be the element and then just like we have next sibling we also have previous sibling which is also going to be a text node so hopefully this gives you a good understanding of nodes in general versus element nodes which is what we looked at in the last video and for the most part you’re going to be working with element nodes so the other properties we looked at like next element sibling previous element sibling parent element uh what else children as the as the an HTML collection as opposed to these child nodes so that stuff you’ll probably be working with more but again I want this to be a front to back course I want you to know everything you know as far as I know all right so that’s it in the next video we’re going to be looking at actually creating elements from our JavaScript okay so we can select elements from the Dom using multiple methods we can navigate to related elements using certain properties and we can manipulate Elements by changing their inner text in our HTML we can change the Styles now I want to show you how we can create elements in JavaScript so we can create any Dom element that we want and then insert it into the document wherever we want using specific methods so in many cases you’ll want to create a new element and then insert it into the document on some kind of event so an example would be with this shopping list ultimately we want to type something in here click the button add item and have it get added to the list now we’re going to go over events in the next section but the next few videos in this section we’re going to do some of the stuff that usually would happen after an event is fired off all right I just want you to know how to insert thing to remove things Etc create things alright so let’s jump into our script JS for this section and what I’m going to do is create a variable here called div because that’s what I want to do is I want to create a new div so we can take our document object and there’s a method called create element so we’re going to run that but we need to pass in the type of element that we want to create and of course it’s going to be a div judging by the name of the variable now we can console log that div and this doesn’t do anything to the page just yet all it does is basically just creates it in memory from our JavaScript it’s not placed in the page just yet now we can add attributes to this div so I’ll go right here and I’ll say let’s do div Dot and we’ve already looked at some of these like class name so let’s say I want to add a class name of my element and if I save now you’ll see that I have a div and it now has a class attribute of my element if I wanted to add an ID I could say div ID and set that to we’ll just use my element again so now it has a class and an ID we can also use the set attribute remember that set attribute method so we can say div dot set attribute and let’s say we wanted to add a title to the div and we’ll just say my element and if I save that now you can see it also has a title so you can create it and then you can add whatever you want to it now as far as what I want to put in it because right now that it’s just an empty div so we can add something to it by using well there’s a few ways to do it the the easy way to do it would be to use inner text so we could do like div Dot enter text and set that to whatever hello world if I save that now you’ll see in the console this div has the text of hello world however using inner text is not the best way to do this when creating a new element it is it’s really meant to Inner text is really meant to get and change the text of an already existing element it’s better to create a new text node with the create text node method and then append it to the element okay because remember when we talked about nodes there’s element nodes there’s also text nodes and we can create those so what I’m going to do is just comment that out and let’s create a new variable called text and set that to document Dot and then let’s say create text node and then in here we’ll put the text that we want in it which will be hello world okay and then we need to add that text node to our div and we can do that by using the append child method so we can say a pen child and then text I save and now down here you can see that hello world has been put into this div now a pen child is a very important method that you’re going to need to understand because you’re going to use it all the time and it’s it’s easy to understand it appends a child to whether that’s an element or whether that’s a tech node a tech node a text node it appends it to or inserts it into whatever this is so in this case we’re putting the text inside of the div now we want to use a pen child to put it on the page as well and where you want to put it or what you want to append it to is is up to you it could be anything so let’s get rid of this console log and let’s say we just want to put it at the at the end of the body or you know at the end of inside of the body we could just do document.body append child and then pass in our div and if I save that you’ll see that hello world is now put at the very bottom so if we were to inspect our element here it’s right before the the ending body tag okay it’s above the scripts and stuff and the live server stuff but it’s after everything else all right now if you wanted to put it let’s say at the end of this UL this this unordered list then instead of document.body we could do document and then we could select let’s say query selector and select the UL and then we could just uh just say a pen child and then append the div there I save and now it’s it’s going to be inside of the UL at the very end now what I want to do in the next video is actually insert an item that looks just like this with the the text and the the button so I’m going to actually give that to you as a challenge because everything you need to know we’ve already gone through and and most of it is right here for you to be able to do that so we can do it as a challenge if you don’t want to you just want to follow along that’s absolutely fine but that’s what we’ll do next all right guys in the last video we scratched the surface on creating elements and adding them to the Dom and there’s two main methods for that one is create element which allows us to do just that and then also a pen child which will allow us to append whatever we want to any element that we want now in this video I want to show you I want to get more deeper into that and show you how we can create a function to add a new list item to this shopping list and it has to include not only the the title of the the item but also the button this is a button that has an icon within it so it has to be the title the title and then the button and then also this I tag with along with these classes and I’m going to show you two ways to do it one is kind of a quick and dirty way of doing it which is using inner HTML and the second is a cleaner and more performant way of doing it where you’re creating all your elements not only the Li but also the button and and the eye tag here all right so and I’m not saying using enter HTML and doing it this the quick and dirty way is horrible it’s not you see it all the time but there is a better way to do it so ultimately we want to have a function which I’ll run down here called create list item and we want to be able to pass in whatever we want like let’s say eggs all right so let’s create the quick and dirty way first so we’ll say function create list item it’s going to take in an item now at the very least you have to create your Li element right I can’t do this I can’t say Li and set that to a string of let’s say Li at our Li tags here and then put in um actually we would use backticks here right because we want to put our item in here okay so we just have a string with list items and the item and then I want to append that to the to the unordered list so I would say document Dot and then we’ll use Query selector to get the UL uh we could do UL but it has a class of items so that’s more specific and then we can do append child and if I put the LI variable in here which is this this string let’s see what happens and this is this is what messes a lot of people up in the beginning it says fail to execute a pen child on node because the parameter one is not the type of node okay what I passed in here this Li is not a node it’s simply a string so this has to be a node meaning we have to actually create the element node and we do that with create element so we want to pass in here Li now the easy thing to do here the cheap thing to do is to just take Li and then set the inner HTML of that to a string or a template string and then I could just copy like all of this everything inside one of these Li tags and then replace apples with whatever that item is all right if I save that let’s see create element oh I forgot document all right so now if we look at the list you see eggs has now been added so we created an ally element node and then we just said well we want the inner HTML to be this and then we simply appended that Li node so next I’m going to show you a better way of doing this a cleaner way and that is to create all of the elements not just the LI but also the button also the I tag here and add the classes so let’s uh let’s call this something different so that we can run both we’ll just say create we’ll say create new item instead of create list item and it’s going to take in an item and let’s just call that down here so we’ll pass in say cheese and we’re going to call create new item all right now to start off here it’s going to start off the same we need to create our list item all right so we’ll say document Dot create element and we’re going to create our list item now we also have a button and an icon so let’s create the button as well I’ll say button equals document dot create element and we’re going to create a button all right and then that button has classes so we can say button dot class name and set that to a string of classes which are going to be these so I’ll grab those and paste those in and we should be able to console log here if we want the button just to see so we have a button with classes on it right now we also want an icon so let’s say const icon and set that to document Dot create element and that’s going to just be an I tag and then that also has classes on it so we’ll say I dot class name and set that to let’s see these two classes right here so we get the x mark all right so we’re setting that I’m sorry that should be icon I was wondering why it was white so now uh oh and one thing we I forgot to do is the text the text for the the LI is going to be a text node right so we’re we’re creating the LI element we’re creating the text node we’re creating the button element and we’re creating the icon element instead of just setting the inner HTML to whatever so for the text node let’s do we’ll just take the list item and then append we’re going to append child because the text node goes inside of it and then we can say document dot create text node we could put this in a variable if you wanted to and the text node is just going to be whatever the item that’s passed in here all right so now we need to put the icon right the I tag needs to be appended inside of the button so we can just say button dot append child and we’re going to pass in here the icon and then the button needs to go inside the list item right we have the list item the button will be appended inside that so let’s say list item dot append child and we want to pass in the button all right and if we do a console log right now of the list item well actually let’s look at the inner HTML in our HTML of the list item and that’s that’s the text node then we have the button with the classes and then the I tag with the classes so the only thing left to do now is to append that to the Dom to uh to the UL which is what we did at the end right here so let’s just paste that in and save and now you see cheese is added now is this a huge deal in this situation no it’s not just know that using inner HTML so using this this first method causes the web browser to re-pass and recreate all the Dom nodes inside the UL element so this is less efficient than creating new elements and appending them so the second way is going to be more performant also setting in our HTML HTML will not automatically reattach event handlers to the new elements it creates so you would have to keep track of them manually I know we haven’t gotten into events yet but it can cause some issues with uh with attaching event handlers but again I’m not going to sit here and tell you that this is a horrible way of doing it and you will see this quite a bit all right now in the next video I want to take it a step further and instead of having just a single function I want to create a separate function for creating the button and creating the icon making it pretty reusable if you want to create other buttons and icons and also just making it more readable all right guys in the last video I showed you a couple ways to add a new list item to our shopping list and one of the ways was kind of a quick and dirty where we just used in our HTML On An Li node and then we also had this function here where we create the LI element the button element icon text node and we just append them all and then ultimately append to the Dom so when it comes to clean code I think a lot of it is preference you know so obviously some things are objectively wrong or right but I think a lot of it most of it comes down to the developer’s preference so in this case if you wanted to keep this as one function that’s fine but to me I think it’s cleaner to cut it down where a function does one thing so we’ll have this create the item but then we’ll also have another function to create the button and another function to create the icon and then it makes it more reusable if you want to create a button or an icon somewhere else all right so this is completely optional what I’m doing here I just want to give you a couple different points of view you know so it’s up to you on on how you choose to write your code but I want to give you the options so so let’s create a function called create button okay because I want this to be a separate function that takes in the classes because each button has classes and then also the same thing with icons so let’s create another function called create icon all right and then basically all we want to do these two lines here we’re creating the button and then we’re adding the classes I’m going to cut that put this into here and then the classes we’re going to cut and then set button dot class name to the classes that are passed in as arguments all right and then ultimately from here we just want to return return the button and then what we can do in the create new item is just set a new variable of button to the return value of uh create button and then we can pass our classes in if I save that we’re going to get the same exact thing now I want to do the same thing with icons with the icon so I’m going to grab those two lines and in our create icon let’s paste that in and I’m going to cut these classes set that to the classes that come in as arguments and then return the icon and then that way we could come up here now this is another thing that you can you have preference on if you want to have the icon or create icon function called in here or in the button because the icon is inside the button so I’m going to choose to actually do it within here so I’ll say const icon set that to create icon and then pass in the classes and then this line here where we’re taking the the icon and appending it to the button that is going to go down here in this function okay so now if I save this we get the same result but to me it’s a little cleaner okay we have a separate create button and a separate create icon we’re just setting the button to the return value of of the create button we’re appending it to the list item and then ultimately we’re appending the list item to the the UL and the Dom all right so if I were to call another function here create new item and we’ll put in I don’t know sauce save that and you’ll see that gets added so it’s completely up to you I’ll talk about like clean code practices and stuff throughout the course but like I said I think a lot of it is preference all right guys so when it comes to inserting elements into the Dom we’ve looked at a pen child which is very common you’ll probably be using that a lot but there are other methods as well that you can use and I want to show you those in this video so the first three are they’re all related it just it’s the only difference is what you’re inserting so we have this insert adjacent element if you’re inserting a new custom element insert a Json text if you’re inserting text and insert a Json HTML if you’re inserting HTML so the way these work is they take in a position which is going to be one of these four so here I just put this example of a paragraph and if you choose to insert before begin it’s going to go above the paragraph okay or whatever element you’re using as a reference and then after begin would be directly inside of it at the top above all the content and then before end would be after the content but still within the paragraph and after n would be after the entire paragraph or whatever element all right so let’s start off with the insert adjacent element and I’m just going to create separate functions to run for each of these so this one will call insert element just so we’re not in the global scope and first thing we need is a reference element on the page so where do we want to insert our new element let’s say we want to do it before this filter items input so we need to bring in that filter items input so let’s say document Dot query selector and I believe that has a div around it with the class of filter so we want to choose that all right then we want to create our new element and this could be whatever anything you want to put on the page whether it’s a new list item or it’s some data from an API whatever it might be in our case I’m just going to create an H1 so let’s say document dot create element and we’re going to create a new H1 and then I’m just going to add some text to that with text content so let’s set this I’ll just put the the name of the method we’re looking at as the text all right and then to insert it we’re going to take the filter and then that’s where we call insert a Json element and it’s going to take in two things the first is going to be the position which is going to be one of these four I’m going to choose before begin all right so that that’ll put it right above it and the second is the element we want to insert all right so now let’s just run this function so that this code runs and we’ll say insert element save that oops and you can see that my H1 has been put above the filter form if I change this to let’s say after end it’s going to be put below it all right so it’s just another way to insert content onto the page through JavaScript now the text insert adjacent text works in a very similar way so let’s create a function here called insert text and we’re going to figure out what text do we want to choose or what element do we want to choose to put our text before or after I’m going to choose the first list item here so let’s say const and say item and document dot query selector and we’ll just put an Li here we could do Li colon first Dash child either one is going to give us the first one and then on that item we’re going to run the insert adjacent text method and that’s going to take in a position let’s say we’ll do after end and then we can put in I’m sorry not item whatever text we want which I’ll just do I’ll just do the name of the method save that actually we have to run it so let’s come down here insert text save that and now you can see that it’s after the first list item if I change it to before begin then it goes above it I can also do after begin that will put it inside or before end which will put it inside at the bottom and this is similar to what a pen child does right so for HTML that’s just pretty much the same thing we’ll say insert HTML and let’s choose let’s choose the clear button down at the bottom so we’ll say clear BTN and document dot query selector and it has an ID of clear and then on the clear button let’s say dot insert adjacent HTML and it’s going to take in a position so let’s say before begin and then we can just pass in basically a string with HTML so let’s put an H2 and we’ll say insert uh insert adjacent HTML and close our H2 save that I keep forgetting to run it insert HTML there we go so it’s put before if I do after then it’s put after okay so again these all work and they work the same way it just depends on what you’re inserting an element a text just regular text or HTML and this is insert HTML or insert a Json HTML works like in our HTML now there’s another function or method that I want to show you called insert before which is similar to a pen child and how it works but it’s a little more complicated because you what you do is you define a parent or you bring in a parent and then you choose the item inside that parent that you want to insert your item before all right so let’s create a function called insert before item and we’ll create the parent or select the parent which I’ll use the unordered list so let’s say document Dot um query query selector and then we’ll choose the UL so that’s the parent now we want to create the element we want to insert which will be a list item so we’ll say document Dot create element and create a list item and I’m just going to add some text to that so we’ll say text content and set that to set it to the name of the function method we’re looking at and then what we do is Select an item inside the parent where we want to insert before so let’s select the let’s get the the third item so I’ll say const third third item and we can do that with document dot query selector and then I’m going to do Li and then we’ll use nth Dash child three okay so that will give me the third one and what I want to do is insert my my li I want to put it before this third item insert before that what’s weird about this is you call it on the parent so on the UL is where I do my insert before uh insert oops insert before and then that will take in your element whatever you know we’re putting in which is our Li and then it takes in the reference which is the third item so if we run this insert before text or what is it insert before item okay and now you’ll see that Oreos was the third one right this is the first one second one third one and I chose to insert before that third item so it put that this is my element my new Li it put it before that third item what’s kind of strange is that you call it on the parent with a pen child you don’t do that you just basically select you know the item that you want to put it inside of and then you call a pen child on that now you might think that since there’s an insert before where is it right here insert before that there’d be an insert after but there isn’t so what we’re going to do in the next video and you guys can look at it as a challenge if you want to try it beforehand is to create our own custom insert after all right so we’ll do that next all right guys so this video can be looked at as a challenge if you want to try it yourself or you can just follow along like you would any other video so we saw in the last video the last lesson that there’s a bunch of different methods we can use to insert elements and other things like text and HTML onto the page and insert before was one of those now you might think that because there’s an insert before there’s an insert after but there isn’t so what I want you to do is create a custom insert after function where you can pass in a new element if you look down here at this example code here if you pass in a new element like this Li that we created and then some item that already exists in the Dom your new item should get put after the the existing so in this case I’m selecting the first li as the existing item and I’m passing my li here in as the new item so it should get put after the after apples okay after the first item and you can use new L for your first uh parameter and then existing L for the second now as far as hints you can remember some of the properties to get parent and sibling elements okay remember we looked at that a few videos back and you can combine some of those I’m not going to say which one with insert before so if you combine these together there is a pretty simple way that you can make this work and you can insert a new element after an existing element all right so if you want to pause the video and try it you can if not just follow along and I’m actually going to copy let’s see I want to go back to that because I just want to copy the this code right here because I want to run this exact code so paste that in and now we want to create our function which is called insert after so insert after and that’s being called right here which is getting passed in this custom element that I want to add to the page so we’ll call that new element and then the next thing we’re passing in is an existing element which is the first list item so let’s say existing element all right now remember some of the the properties we looked at such as parent element so if I were to console log my existing element and then the parent element of that I’m going to get the UL okay so I have access to that unordered list and you could use parent node in this case as well if I do parent node that’ll give me the same thing so what I want to do is take the the parent element so existing l dot parent element and then I’m going to call on that insert before okay so remember this from the last video what insert before takes in it gets called on the parent and then what it takes in is the new element that you want to insert and then whatever you want to put it before now obviously we want to put it after that’s what this function is supposed to do but we can go ahead and take the existing element now if I run that and save it insert me after it gets put it actually gets put before apples which obviously isn’t what we want we want this to insert it after but all we have to do is simply add on to the existing element the next sibling property save that and there we go now it’s put after because if we put our new element before the the existing elements next sibling which is the next one orange juice that’s the same as putting it after apples okay so hopefully that makes sense and that’s why it’s important to understand these properties like parent element and next sibling and methods like insert before now I’m not saying you have to remember all these right now but at least know that that they exist and know that you can go on the mdn docs and you can look them up if you need to and and I still need to reference this stuff even for this course there’s plenty of stuff that I had to go and reference but I know it’s there and I know that these things are possible and I’m sure that for some of you this this challenge seemed like really difficult where you didn’t even know where to start but then you see the answer and it’s like one line it’s it’s easy so hopefully this this helps some of you guys out let’s see in the next video we’re going to start to look at replacing elements in the Dom all right guys so we know how to insert elements into the Dom Now using multiple methods now we’re going to look at replacing elements and some of the methods that we can use for that so we’re going to be working with our shopping list UI again and we’re going to be replacing some of the list item elements in this in this shopping list and there’s of course more than one way to do this so I’m going to show you a couple now I’m going to create a couple functions just because we’re doing a few things so I want to be able to to run separate functions so let’s create a function and we’ll say replace first item okay so I want this function to replace the first item which right now is apples so first we want to bring in the item we want to replace so we’ll call this first item and we’ll select that from the Dom with query selector and just put in here you could do LI or you could do first child either way it’s going to select the first one and then we want to create our new element so document dot create element and notice we’ve been kind of repeating ourselves quite a bit throughout the this section and that’s a good thing because it’s drilling into your head how do I select elements how do I create them and start them and so on now we want to create a list item to replace it and I’m just going to add some text content and you can use text content or inner text and let’s just make that say replaced first now to replace and this again this is just one way we’re going to use the replace with function or replace with method so we call that on our first item because that’s what we want to replace and we’re going to call replace with and then simply pass in our new element all right so let’s run this function save that and you’ll see replaced first okay so that’s the first way of doing this is using replace with the next one let’s call this function replace second item and in this in this function we’re going to use outer HTML okay we’ve used inner HTML quite a bit and that pertains to the HTML that’s in the element outer HTML will also include the HTML for that element so in this case the LI tags so let’s get the second item first of all so second item and we want to get that let’s say query selector and to get the second one we could do Li and then use nth child and two so that’ll get the second item and then on the second item we’re going to set the outer HTML and set that let’s say Li and then replaced second Li okay so it’s it’s similar to setting the inner HTML except we’re also setting the outer tags if I save that actually I have to run it of course so let’s say replace second item and now you’ll see replace second now the next one I want to show you is is how we can replace all of the items in the list and there’s not a specific method we’re going to use for it what we’re going to do is Loop through all the Li’s with a four each and then change the outer HTML for each one and if you want to try this on your own of course you can do that as well so let’s call this replace all items and what we want to do is get all of the list items so we’ll just call this Li’s and then we’re going to use Query query selector all since we’re getting more than one and we want to get all the LI tags all right now since query selector all returns a node list we can use for each on that so let’s say for each and we pass in our function here and we’re going to pass in we’ll call this item but I also want to get the index as well okay and then here what we’ll do is just set the let’s say item for each item we’re going to set the outer HTML and let’s just set it to replace all okay and then if we run that down here let’s say replace all items and oh I forgot the Li tags okay so we could do that we could also use inner HTML like I could do item dot enter HTML and in that case I would just do replace all because I’m not replacing the the LI tags so you can see that does the same thing um if I wanted to choose a specific item and and do something else I could do that so for instance let’s say if the index is equal to let’s do the second one so we’ll choose the index one then Let’s uh let’s see we’ll put this actually I’ll just copy that and then let’s say this is the second second item else then we’re going to have replace all so if I save that now you’ll see second item now why don’t you guys go ahead and shorten this up so this for each right here we can have an implicit return we don’t need to use curly braces and we can use a ternary instead of an if okay so if you want to pause the video and try that you can but uh actually let’s go under the four each but all we have to do is say for each and pass in here function we’ll say for each item and we also want to get the index and then here we’ll we’ll just say the item Dot we’ll use outer outer HTML so we want to set that to a condition okay or a ternary so we’ll say if the index is equal to is equal to one then we want this this outer HTML to be list item and then second item okay else then we want this to be a list item and just say replace all or we’ll just say item like that okay so if I comment this one out and save then we get the same result it’s just a little cleaner and a little shorter now another way that we can replace something is by selecting the parent element and then using a method called replace child so I’m going to create another function here let’s call this replace child heading and what I want to do if we look at the HTML here in the header there’s an H1 that says shopping list so I actually want to replace that with an H2 so the way this works is we select the parent which is the header we select the item we want to replace and then we replace it with a new item so let’s go ahead and first of all select header so that’s going to be let’s say document dot query selector and that has I will just select it by the the element itself which is header and then let’s get the H1 so H1 and we’ll say header H1 and then let’s create a new element we’ll call this variable H2 say document dot create element create an H2 and let’s add an ID because I believe that has an ID or it doesn’t okay but we can still add an ID we’ll say dot ID equals app dash title and then for the content let’s say text content and I’m just going to keep the same shopping list okay and then all you have to do is on the header we can do replace child and we want to replace we want the H2 to replace the H1 all right so let’s run that function replace child heading save that and now this should be an H2 so if we check it out there we go H2 and it has the ID of app title okay so those are some of the ways that we can replace elements in the next video I want to show you how we can remove elements okay so now we’re going to look at removing Dom elements now just like with most of the stuff that we’ve talked about in this section the things we’re doing we’re usually going to do when we fire off an event such as click this delete button right here then we would remove this all right but I just want to show you that the methods to manipulate the Dom before we get into events and we’ll get into events in the next section so so there’s basically two methods I want to show you remove and remove child so they’re pretty self-explanatory remove is going to be called on the element you want to remove remove child is called on the parent element and then you pass in the item you want to remove so I’m going to give you a couple examples in the form of functions so let’s say we want to remove the clear button so all we have to do here is Select say query selector and we’ll select the clear button which has an ID of clear and then we can just call remove okay and then if I come down here and I say remove clear button and now it’s gone and you could put this you know you could put this into a variable like say clear button and then what you could do is just call on clear button variable removed same thing all right now the next one is remove child so I’m going to create a function called let’s say remove first we’ll say remove first item and we want to since we’re moving using remove child we want to get the parent which is the UL so let’s set that to document dot query selector and select the UL and then select the item we want to remove I’m going to call this variable Li and then as a selector we’ll pass in Li and we’ll do first child or you could just do Li so that’ll select the first one and then we want to call on the parent on UL we want to call remove child and then we’ll pass in our Li and then if I call that let’s say remove first item and now you’ll see apples is gone so that’s remove and remove child now we’ll do a couple other things just to you know explain it a little bit further so let’s create a function and let’s just call it remove we’ll just call it remove item and then I wanna I wanna pass in an item number or index and it’ll delete that item right so if you want to try this yourself then you can pause the video and do that but I’m going to comment out this remove first item so we have our apples back and what we’ll do is I’m going to show you a couple ways to do it we’ll use remove child in this one so we’ll get the UL so UL equals document dot query selector we want to get the UL and then for the LI let’s see I’ll just copy this down the LI we want it to be the specific item number and I want the item to be one two three four so so what we could do one of the ways we could do this is to put in backticks here for our selector and then do Li and then say nth Dash child and then in here we can put our variable of item number so that way if we come down here and we call remove item and we pass in one and save let’s see that didn’t work oh we did I didn’t actually call the remove so UL dot remove child and pass in the LI variable and now apples is gone if I pass in 2 then orange is gone all right now another way to do it is let’s see I’m gonna I’ll just copy this but I’m going to call this remove item 2 I guess and instead of we’ll still use remove child but instead of passing the variable into this pseudo selector I’m going to query selector all because remember what that gives us if I select all Li’s is an array-like structure called a node list and we can access the index so I can do this and what this will do is put the very first one the zero index which is Apples into this Li and then I I’ll remove that so to give you example let’s say remove item two and it doesn’t matter what I pass in just yet I’ll pass in one but Apple’s is still gone because I have 0 here so what I want to do is this item number I’m going to put that in here however remember it’s zero base so if I pass in one here like I am right now and I save it gets rid of the second one which is orange juice because this is zero base but I’m not making this like I don’t want to pass in zero so all we have to do is take that item number and just subtract one from it so now if I pass in one apples is gone if I pass in two then orange juice is gone all right now I’m going to give you one more example so let’s say function remove item and we’ll call this remove item three it’s going to take in item number now I don’t I’m going to use remove in this one instead of remove child so I don’t need to get the parent so what I’ll do is uh I’ll just copy this line here and I’m going to get all of the list items so I’m going to just get rid of these brackets here so we’re getting all the list items and then we can simply do Li which is a node list which is array like so we can say item number subtract one because it’s zero based and then on that item or on that element we’re going to just call remove so let’s go ahead and say remove three we’ll put pass in a one here and that should get rid of apples if I pass in 2 gets rid of orange juice pass in three gets rid of Oreos all right and uh and we can really shorten this up actually we could say const remove item three let’s call it four so remove item four and let’s make that an arrow function that takes in the item number and then it’s gonna return let’s say document dot query selector all right so query selector all and then we’re going to pass in here item number minus one and then call Dot remove so if I come down here we call remove item four and I pass in one that didn’t work let’s see oh I forgot to put the actual Li in here and there we go so now apples has gone now orange juice is gone so this is just a shorter way of doing this all right so that’s it in the next section we’re going to start to look at events which I’m sure a lot of you have been waiting for all right so what I want to do in this video is look at some of the properties we can use to manipulate CSS classes and just our CSS directly which we’ve done a little bit of this already but I want to really just just drill it down here so we’re not using the shopping list UI we just have uh we have a paragraph that has a class of card I have just this background and border and then a UL that has a class of item lists and items because I wanted to have something that has multiple classes and then a button that says run now we’re going to go over events in the next section but I wanted to have an event a button click here because 99 of the time when you’re changing classes and changing Styles it’s going to be on some kind of vent it’s not just when the page loads you would use CSS to just simply add Styles when you use JavaScript with CSS is when you want to have Dynamic functionality if you click on something like if you wanna display a menu or something on click like a hamburger menu that’s where you would use these kind of classes and and style manipulation as far as the style sheet I just have just I just changed the font I have a class of hidden with display none you’ll commonly see this if you want to hide something then we have a class of card that just designs this background here with the border and a class of dark which will give it a darker background and I haven’t used that yet anywhere in here so let’s jump into the script and I just want to bring in what we need so I’m going to bring in the paragraph so let’s say document dot query selector and we’ll select the paragraph all right then we’re going to Let’s copy this down we’re going to grab the item list so we could either put UL in here but it’s better to Target a class or an ID so let’s say item list and we’ll call this item list and then I also want to get all of the items so we’ll call this items and then what I’ll do is on the item list I’ll call query selector all and we’ll select all of the list items all right now as far as the The Click event goes I’m going to select the button so we’ll say query selector and select button usually you should have some kind of ID because you probably have multiple buttons on your page but in this case it’s fine and then I’m going to do dot on click okay and again I’m going to talk about events all in the next section that’s what the next section is based on so don’t worry about it right now if you don’t understand it but we’re just going to set the on click event to run a function called run and you don’t want to put parentheses here because that will automatically execute it so up here let’s create a function called run and if I just do a console log here and then let’s open up our console if I click it you should see a one all right now this is where I want to show you the different properties so the first one is class name so if I do a console log here of let’s take the item list and let’s say class name and I click this it’s going to show me all of the class names okay it’s just basically it gives you a string of all the class names now you can set the class name as well like I can say item list and let’s say dot class name and let’s say I set it to that dark class all right now actually you know what I want to use the the paragraph for this so the text so if I click on run notice it applies the dark class and we can check that out right here but it took the card class away so this is always going to overwrite whatever classes you have there so if you do do it this way you need to make sure that you also put the existing classes so in that case I could do that and then that would keep the Cod class as well all right now A Better Way for dealing with this is to use the classless property the classless object which has different methods you can use on it to add and remove classes or even toggle classes so let’s look at class list all right now if I were to console log here let’s say item list Dot class list okay so I’ll click let me just um we’ll comment this stuff out for now so if I click that you’ll see what we get is a it’s actually called a Dom token list which is similar to an array it’s basically an array of our classes all right and I could even Loop through that with a Dom token list you can use methods like for each so if we say item list Dot classlist dot for each and I’ll say for each class then let’s do a console.log of that class so now if I let me just comment this this one out so if I click run now you’ll see it’s just going to log each class so you can take each class and do whatever you want with it in this case I’m just logging it out now to add a class like let’s say we want to do this same thing we want to add the class of Doc but we also want to keep the class of card so I could take the text and say dot class list and then there’s an ad method that we can use and I want to add the class of Doc so now if I click that and that runs you can see it still has the formatting from the card class it just added the new class of Doc all right now we also have a remove so if we do let’s say dot remove and let’s remove the card class which will take away the padding and the the border and stuff so what happened is it added the dot class and then it removed the card class so there’s no more padding now we also have a toggle class which is very useful so let’s comment that out and Let’s uh let’s say text Dot class list and then we’re going to use toggle and let’s toggle the doc class so this is good if you want to have like a a doc light switcher a lot of websites have those so if I click on run it turns dock if I click it again it then removes the class in fact let’s go ahead and take a look at that you see this paragraph click run and dark it’s added click it again it gets removed so that that’s something that is very useful when you’re creating dynamic dynamic websites now I could also do let’s say we want to toggle the hidden class so what that’ll do is when I click it it goes away click it again it comes back so pretty cool now there’s also a replace class so if I wanted to do let’s say text.classlist I don’t use this one as much but it is available so if we wanted to replace let’s say we want to replace card with Doc so it’s going to take in two arguments so if I click now you can see the card is gone there’s no padding and the dot class has been applied so it just replaced it now if I want to change the style directly let’s say change Style then we could use the style property and we’ve already done this a few times but let’s say we want to take the I don’t know take the item list and let’s say Style and let’s change the line height now in normal CSS you would do line Dash height but we can’t do that here so if you have multiple words we just use camel case so it would be line height like that and we’ll set that to let’s set it to three so now when I click the button you’ll see that the line height is applied so you can do that with any CSS style or any CSS property if I wanted to change let’s say I wanted to um do something to all of these list items what I could do is there’s a few ways to do this but I could Loop through these right so item list I’m sorry not item list items which is the query selector all and let’s say for each actually I’ll put some parentheses in here because I want the item and the index and then for each item you can do whatever you want so let’s say we want to style the color and set that to Red all right so now I click that and all the items turn red and you can Target specific ones like let’s say we want to say if the index is equal to two then let’s make that item Style color we’ll make that one blue so now if I click it you’ll see that the third item is blue because that’s the index of two all right so that’s really the basics of of just dealing with uh classes and style in JavaScript all right guys so now that we’ve looked at all kinds of methods and properties on the document object to be able to add change and remove things from the Dom now we need to learn about the actions that the user takes to make these things happen and those are called events and any interaction that the user has with your web page all the way down to the actual loading of the page is an event and we can listen for those events and create something called event handlers so in this section we’re going to learn about all kinds of events most and keyboard events form submissions event delegation and bubbling and and much more so with the knowledge between this section and the last section you’ll be able to create some cool little front-end applications and then after this section we’re going to start on the shopping list project and we’re going to build that from scratch all right so in this video I want to show you how to listen for events but first of all what are events so the official mdn explanation is that events are actions or occurrences that happen in the system you are programming which the system tells you about so your code can react to them so that’s kind of uh an Overkill of an explanation basically an event is just when something happens okay or an action and that could be anything from the web page loading to clicking on an element typing into a text field hovering over an element submitting a form closing a window dragging an element resizing an element etc etc so just about anything is an event and you can listen for those events so that’s what I want to show you how to do now so I’m going to close that up and I just have our our good old shopping list UI here with an empty Javascript file and there’s a few ways that we can add an event listener onto an element so the first way I’m going to show you is is not recommended I don’t think any JavaScript developer would recommend it because it’s not flexible it can also pose a security risk and that is to put the listener in the HTML file as an attribute so for example this this clear button that’s what I want to work with so we could put in here an on click attribute and then I could actually put a JavaScript expression right in here like I could say alert and say clear and now if I come down here and click the button I’m going to get an alert box with clear all right now obviously you can only put so much JavaScript in here so you could actually put a function like on click or let’s call it on clear and as long as I have my script file linked to my HTML here I can create a function called on clear and then I can alert and we’ll say clear items all right so if I come over here and I click again we get an alert box with clear items but again this is not recommended you don’t want to have your HTML cluttered up with what are called inline listen event listeners so we’re going to get rid of that and then I’m going to show you the second way which is to use a JavaScript event listener so with this we can select our element let’s see I’m going to keep the on clear here but I want to comment it out but I’m going to bring in the clear button because I’m going to use it in a few different places so let’s say clear BTN we’re going to select it with query selector and it has an ID of clear all right so what we can do to add an event listener within our JavaScript is to say clear button and then just do a DOT on click and on click is one of many event listeners and then you would set that to a function and then do what you want in here so let’s do uh we’ll do we’ll do an alert so we’ll say alert and clear items okay so if I come over here I click and I get my alert box and I didn’t have to do anything in the HTML so that’s the second way the Third Way is what I would recommend it’s the most modern way and it’s what we’re going to do in this for the rest of this course and that is to use the add event listener method and what that does is it just allows you to do just that you take an HTML element or a Dom element and you add a listener for a specific type of event so let’s comment this out for the moment and let me just say add event listener so we would once again just take the clear button or whatever we want to put the listener on and simply say add event listener and then this takes in two arguments it’s going to take in the type of event which in this case I want it to be a click and then it takes in a callback function so I’ll just put an anonymous function in here and then I’ll do an alert and we’ll say clear items save that and if I come over here and click I get the same thing all right gives us the same result now you can shorten this up we can go ahead and turn this into an arrow function so we can do that and since it’s just a one liner we can even get rid of the curly braces like that and that should still work all right so this is what I would recommend and another kind of Advantage with this is you can have as many event listeners as you want on the same event and let me just show you if I uncomment this and then I copy it and then let’s say I want to do I want another event listener on the clear button and this time I’m going to just console.log clear items all right I’m going to comment this out for a minute so we have two event listeners same event same element but they do two different things so now come down here and let’s open our console and let’s click and you’ll see we get our console log but I never get that alert okay if I comment the second one oh then we should get the alert now with add event listener we can have as many as we want so I’m going to just copy this down and let’s see instead of on this for on the second one instead of alert let’s do console.log and now if I click this you’ll see we do get the alert and then when it once I clear that up then the it console logs all right and the reason that it doesn’t run at the same time like you don’t see the log at the same time is because an alert is a blocking operation and I’ll talk more about that when we get into synchronous versus asynchronous code but just know that an alert is it’s synchronous and it’s blocking so nothing is going to happen until that’s cleared up all right but it does run both of them so that’s an advantage of add event listener now for these we put in just an anonymous function but we can use a named function such as on clear so I’m going to just uncomment that and I’ll just comment one of these and then instead of passing in this Arrow function as the second argument let’s pass in the on clear function now when you do this you don’t want to put parentheses if I do that it’s just going to execute okay the function gets invoked because we’re using parentheses so you just want to pass in the Callback you want to pass in the function name so that way it only fires off when you fire the event all right now there is a remove event listener method and you don’t have to use it every time you add an event listener where you do want to use it is when you have an element that you’re removing from the Dom like we learned about the remove method remove child if you’re doing that then it’s a good idea to remove the event listener first so what I want to do is is call remove event listener but I want to call it five seconds after the browser low after the page loads and I’m going to use a function called set timeout to do that which we haven’t used yet so it might be a little confusing but we will get into set timeout which is an asynchronous JavaScript function and we’ll get into that later but basically it takes in two things a function and then it also takes in the number of milliseconds that I want to wait to fire this function off and I’m going to say 5000 which is five seconds and then in here is where I want to remove the event listener so I’ll say clear BTN dot remove event listener and what I’m going to pass into this is the event which is click and then I also need the reference function which is on clear okay and which we we have up here okay so that’s the function being passed in to add event listener also the function being passed in to remove out of uh event listener so if I save that you’ll see that this works fine I’m clicking it it’s it’s you know the box is popping up but once we get to five seconds you can see I can no longer click it because that event listener has been removed now the last thing I want to show you before we make this actually function and clear these items is that we can trigger an event programmatically so if I wanted to have my script actually do the click instead of coming over here and clicking I can do that so I’m going to actually use set time mode again because I want this to happen after a certain amount of time I’m going to comment this set timeout and once again we pass in a function and also the length of time we’ll do five seconds and I’m going to take the clear button and then from here I can do dot click like that okay so if I save that and then we just wait five seconds there we go we see the the alert box okay so we have this this event to this click event and here we’re waiting five seconds and then we’re basically clicking this just from within our script rather than coming over to the browser and clicking the button all right because there might be some cases where you need to do that where you need to actually fire off an event from um you know from your script so now what I want to do instead of just having this alert clear items is make this actually work or we click clear and all of these go away so what I want you guys to do is pause the video and see if you can do it and see how many different ways you can make that happen just for from what we’ve learned so far there’s there’s many ways you could do it so just pause the video and see if you can do that all right so the the easiest way would be to just take the uh not the clear button we need to have the the unordered list so we’ll say query selector and we’ll select the uh unordered list actually I’m going to put this in a variable let’s say item list okay now when it comes to setting these in variables it’s all preference if you’re just using it once in one function then I mean I would probably just use document query selector and not put it in a variable if you’re using it a bunch of times in your function then do something like this if we’re using it a bunch of times in the script then put it at the top you know in the global scope but different people have different preferences so what we could do is simply take that item list and set the inner HTML to nothing that would be the easiest way to do this clear it all right it isn’t the most performant but you’re not even going to notice a difference because this it’s such a simple task so that’s the first way of doing this second is to bring in the the actual list items so we’ll say items and we can set that to item list and then use Query selector all and select all of the list items and then we could Loop through the list items so items dot we could use a four each and that’s going to take in function we’ll say for each item then we want to do an item dot remove okay so if I do that I click clear they’re all going to go away all right and then the last way I want to show you is using a while loop and I I guess this is the most performant way to delete multiple items like this so we’ll say while it’s it’s a it’s a way that I didn’t really use before a little while ago so we can say item list and then we can use the first child property to just check to see if there’s a first child if there’s a first child that means that there’s there’s a list item and then we can take the item list and use remove child let’s say remove child and then we can pass in the first child with item list Dot first child all right so we’re basically checking for the first li if it’s there then we’re going to remove it and it’s going to do that until there’s no more children and that just fired off because of this let me just comment that out okay so I click and they go away all right so that’s it in the next video I want to start to look at some other Mouse events other than just click okay so now we’re going to get into some of the mouse events that we have that we can listen for and we’ve already looked at click but there’s many others as well so I’m going to just pick something on the page to assign these event listeners to I’m going to use the logo so I’ll say document dot query selector and I’ll just select the IMG because it’s the only IMG on the page and then I’m going to put all my event listeners at the bottom of the page which is my preference if I have my event listeners hooked to a function I like to put the functions up top and the event listeners at in the bottom so let’s do a click just so just to be consistent and have all the mouse events I know we’ve already looked at it but we’re going to say add event listener and we’re going to listen for a click and then we’ll have a function called on click all right and then we’ll create that function up here I’m going to use Arrow functions just to keep them shorter so I’ll say const on click and then I’m just going to do a console.log and say click event all right so if I come over here to the logo and I click I’m going to see click event so the next one I’m going to show you is double click now what we call the function like right here I can call it anything we’ll call this on double click this is is where you need to be specific so double click is DBL click and it’s all lower case it’s not like this right if you if you’ve used jQuery before and used events there it was camel case but in this case it’s going to be all lower so let’s copy this down and we’ll say on uh double click then let’s say double click event so now if I come over here and I if I click once I get click event if I double click I’m still going to get my my two click events but it’s also going to fire off the double click event all right and just to make this a little more fun let’s actually put some curly braces here make a code block and let’s have it do something else so I would encourage you if you’re just learning this stuff I’d encourage you to to just create events and just do some weird stuff you know like maybe we can take the body uh background color and change it so we’ll say style Dot uh background color and we’ll set that to purple so now if I come over here onto the logo and I double click we get a background of purple and maybe we want to toggle it so what we could do is put an if statement around this and say if it’s not equal to purple then we’re going to make it purple and we’re also going to make the text White so go like that and then set the style color to white else because we want to be able to toggle it so else then we’re going to set the background to White and we’ll set the we’ll set the text color to Black all right so now if I come over here and I double click changes the background in the text color I double click again it goes back to White and I can toggle it right because we just we have an if statement we’re checking that background color all right so I mean I know that’s kind of pointless and stupid but it helps you learn so I would encourage you to just do stuff like this as you’re learning all right the next I know that was kind of a tangent but the next one is to if you want to right click and the event is not called right click it’s called context menu because that’s what it usually does is open up a context menu but I’m going to call the function here on right click and then I’ll just um we’ll grab that and let’s change this to on right click and we’ll say right click event and again if you want to do something else other than just a console log you can but you’ll see now if I right click the context menu opens up but it also shows me the the console log okay the next one is the mouse down and mouse up so let’s do mouse down and then we’ll call this on Mouse down now oh we need to create our function say mouse Mouse down event and we’ll call this on Mouse down okay so what this pertains to is when you when you take your mouse and you just click and hold see I’m holding the the the left button down right now that’s the mouse down okay when I let go then it’ll say click event because the click consists of down and up a mouse down is just when you hold it down because you might have something maybe you’re creating a game where you like click and drag or something like that and you want to have something happen when that as soon as that mouse goes down and at the same time you can also have a mouse up so let’s say on Mouse up and we’re going to listen for Mouse up and we’ll just copy that up on Mouse up and Mouse up alright so now if I come over here and I click and hold I can see the mouse down event when I let go we’re going to see The Click but we also see the mouse up okay so most down Mouse up next one is wheel so if you want to have an event on the mouse wheel and the event is is called wheel so bring this down and let’s say on Mouse wheel okay so now if I just if I scroll and I’m not over that the the logo the the item with this that this is on then it’s not going to do anything down here but if I come over it and I scroll now we’ll see the mouse wheel event and it’s going to fire every time I do a little you know a little scroll or whatever so those are are the events for the buttons now we also have events for hovering there isn’t an actual hover event that I know that for me back in the day when I learned JavaScript I also learned jQuery at the same time which I wouldn’t recommend and there’s a hover event in jQuery but with JavaScript you have Mouse over and mouse out so let’s say let’s copy this down and let’s say mouse over and then we’ll say on Mouse over and then let’s copy this down and say mouse over event on Mouse over all right so now you’ll see that when I go into the logo that Mouse over event fires off okay if I come out it doesn’t do anything if I go back in again so every time I go in then it’s going to fire that off now the out does the opposite so let’s say on Mouse out and the event is called Mouse out and out all right so now if I go in I get mouse over if I come out I get mouse out all right so that’s how that works and then the last couple I want to show you have to do with dragging so let’s do we’ll get more into drag and drop later but the first one I want to show you is drag start so we’re going to say on drag start and the event name is drag drag start oops and then let’s go up here and copy that down we’ll call this on drag start drag start event okay so now what I’m going to do is come over to the logo I’m going to click and hold and then move it okay so you see that it only fires off when I click and I drag it it only fires once it doesn’t like keep going when I’m when I’m holding it and moving it around that’s the drag event so that’s what I want to show you next so if we do let’s say on drag and just drag and then we come up here and just say on drag and drag events so now as soon as I grab it and I pull it’s going to say drag star but as long as I’m holding on to it even if I don’t move barely it still is just going to keep firing off and the faster I go the faster you know the event is going to go off so that’s drag and then you also have drag end for when it ends so let’s say on drag end and say drag and drag and all right so now if I grab it so we can see drag and then when I Let Go we should get that drag end oh I put I did camel case here so if I let go there we go drag end event so it’ll just keep dragging until I let go and then we get the drag end all right so those are Mouse events in the next video I want to before we move on to like keyboard events and stuff I want to look at the event object so there’s actually an object when we fire off an event that we can get as uh as a parameter here that we can use to to get all kinds of information so I want to look at that in the next video all right guys so in this video I want to take a look at the event object that’s available to us when we add an event listener and then we run a function so these right here are just some of the properties on the event object that I want to take a look at we’ll get to that in a second but first let’s go ahead and take an element from the Dom let’s just do the logo again so that’s the image and I’m gonna add an event listener onto that so logo dot add event listener we’ll just use a click event and then I’ll pass in a function here now these functions that we pass in can take in an optional event object and you might see it as e you might see it as event you might see it as EVT e is usually what I use it’s just preference but it could it could technically be anything and then let’s just do a console log of that event object so now if I come over here and I click on the logo we’re going to see this in the console so this is the event object with a bunch of different properties and methods on it okay and these these are all in here but it’s not all of them I’m not going to go over every single one right now some of these you just will never use anyway now this doesn’t matter if you pass in an anonymous function like this or if we create a separate function like let’s say function on click so even if we do it this way we’re still going to have access to that event object so what I’ll do is just replace let’s replace this with that named function of on click and if I click on the logo we get the same thing all right now the first two that I want to show you are Target and current Target so Target is the element that triggered the event all right so basically the element that you click on so let’s go ahead and log e dot Target in this case when we click on the logo we’re going to see the image tag because that’s that’s what we clicked on now the current Target is the element that the event listener is attached to now in this case these are the same right so whether I do current Target or if I do current Target so if I do that I’m going to see image twice because it’s the same thing right it’s I clicked on the image and the event is also attached to the image now it can be different I’m going to show you that in a second but I just want to mention that you can use this e dot Target or current Target most of the time you’ll probably be using Target but you can use this to do certain things to that element so for instance I could take e dot Target and then take the style and change let’s say the background color and set that to Black so if I click this now you’ll see that the background turns black so if you need to access the event that’s clicked on you can use e dot Target and you can do anything to it as if it were just an element you brought in with query selector all right now as far as the difference here I want to show you I want to show you where it would be different so if we put on the body just document.body and then we add an event listener right so add event listener and we do a click event and then we have a function and then I’m going to copy both of these console logs here and paste this in now if I click on let’s say this this list item right here if I click on that oops I forgot to pass in the the event object if I click on that you’ll see I get two different things here because the the event is put onto the body and that’s what current Target is it’s whatever the event is attached to the Target is whatever I clicked and then in this case I click the LI which is in the body so basically what happens is events bubble up if I click on the list item that event bubbles up to the to the parent which would be the UL and then bubbles up to that pattern and that parent all the way up to the body up to the HTML and I’m going to go over event bubbling soon but that causes us to get two different things for Target and current Target if we put a listener on something like the body when we put it on the image there’s obviously nothing is is like is nested inside of that that would click on we’re clicking on the image and that’s where the event is but there is a difference between those two all right so let’s look at some of these other ones we have type so I’ll uh let’s see I’ll just comment these out and let’s console log e DOT type so now if I go and I click on the logo the type is a click so that’s that’s the type of event that was triggered okay so if you want to access that the timestamp so I guess we’ll just copy that down and let’s say time stamp if I click on it that gave me undefined that’s because it should be an uppercase s okay so it gives us a time stamp and that’s going to change obviously whenever I click on it but if you need to access that for some reason then we also have these positioning coordinates so client X and client y this is the X and Y position of the mouse click relative to the window all right so let’s try that let’s uh let’s do e dot client X so the x-axis is always going to be horizontal okay so it’s from right to left and then Y is going to be top to bottom so if we save that and let’s click on the corner of this this image right here and you might get something slightly different but what we get is 27 and 58. so what that means is my cursor my my arrow when I click is 27 over from the left on the x-axis and 58 down from the y-axis if I move down a little bit you’ll see now I get 26 for the X and I get 105 for the Y because I’m further down okay so that’s what that those coordinates are now we have some other ones as well like offset X and offset y that’s going to be the mouse click relative to the element all right so what I’ll do is um let’s copy these and then what are we looking at offset so we’ll take these and change that to offset and now if I click in the corner here I get 10 and 11 so I’m slightly over to the left and down if I go up a little bit and over to the left 3 and 8 if I come way down here to this corner 42.53 so it’s the coordinates of where I click within this element okay not from the page like the client but the offset is going to be within within that element then we have the page X and Y which is going to be the position of the mouse click relative to the page okay not the window but the page which is going to be very similar so uh if we were to let’s go let’s change this and this to page and if we come over here and click if I click Like right here it’s going to be from the page you know from the the y or the x is 29 and the Y is 61. now if I make this bigger to where this is pushed way over and I click now you see we get 503 on the X so there’s a lot of space right here and still 62 here that that’s not going to change unless I resize the browser the other way all right so that’s getting the page now you can also do the screen there’s a screen X and Screen Y and that’s going to be your entire monitor so if we were to do that and this is going to be different depending on the size of your screen I have a Ultra wide so the x is going to be pretty large so if I do that so we get 366 from the top and 2916 from the from the left all right so and there’s others those other properties on here but I’m not going to go over every single one right now let’s see I wanted to talk about the method prevent default that’s something that you’re going to use quite a bit when you’re dealing with forms and what that does is it stops the prevent default of the behavior and with a form when if you’re if you’re dealing with front-end JavaScript for validation or maybe you’re making a fetch request or whatever it might be and you don’t want the form to actually submit to the page then you would use prevent default okay you could even use it on a link so if we come over here to the HTML and they’ll just put a temporary link somewhere in here all right so let’s just say we have a link to say Google Google and save so right now if I click on that obviously it takes me to Google but let’s say I want to put an event on that link and I want to stop that that behavior of bringing me to google.com so I’ll say document dot query selector and it’s the only link on the page so I’m just going to use a and then let’s add an event listener oops let’s say we want a click event and then we have our function pass in our event object and then instead of going to the page I want to stop it with prevent default which is a method so we want our parentheses okay and then let’s say I just want to have a console log instead and just say link was clicked so if I save that now and I come over here and I click the Google link you’ll see it doesn’t take me anywhere because of this it’s it prevents the default behavior and then it will do whatever JavaScript I have underneath okay so like I said that’s really common when you have when you have a form that you don’t actually want to submit to a page because you’ll see it actually submits to this page you see how that changes to the the spinner you can stop that with event e dot prevent default which we’ll be doing quite a bit throughout the course now some of these values can be dynamic like the the client X client y if we have let’s say a drag event then that will constantly change so let me just give you uh give you an example here so I’m gonna see we’ll just add another event listener to the logo let’s say logo dot add event listener and this time I’m going to listen for a drag event remember we looked at that in the LA I think it was yeah the last video and then we’ll do on drag oops I don’t want to do that so we’ll create a function here called on drag and we’ll pass in our event object and then what I want to do here we could console log but let’s go ahead and add it to the page so we’ll select let’s say query selector and we’ll select the H1 and then let’s set the text content and set it to some back ticks so a template string and then we can say we’ll say x and then we’ll give the x value by putting in a variable or a JavaScript expression here of e dot client X remember because we have access to that event object so we can use that for anything all right then we’ll do y and let’s put in here e dot client y so now if I save and then I click on this and drag it you’ll see that the H1 now changes to the X and Y values so that’s how you can create really Dynamic stuff within the browser like games and and so on is tracking positions and using events but this is what I mean when I say just try out like stupid little things like this which obviously doesn’t make much sense you wouldn’t have this in a real project but it gives you practice on everything really creating events selecting items or elements using the event object whatever okay so that is the event object we’ll be using much more of it throughout the course in the next video we’re going to look at some keyboard events all right guys so now we’re going to look at some keyboard events we’re also going to look at certain properties on the event object when we use these keyboard events and the element that I’m going to work with is this item input right here so when we type in here we want to basically detect these keyboard events and there’s three main ones that I’m going to show you key down key up and key press so let’s start off by bringing in that input I’m going to call this item input and I’m just going to use get element by D just to switch things up a little bit because it has an ID of item input item Dash input all right so we have this element and now I’m going to take that item input and add an event listener onto it and let’s listen for the key press event and when that fires off then we’re going to run a function called on key press all right we’ll come up here and let’s create a function I’m just going to use an arrow function and we’ll say on key press and remember when you use an arrow function if you only have one parameter here you don’t need you don’t need parentheses around it although my editor will add them automatically when I save but let’s go ahead and just console log here for now we’ll just say key press so we know when that’s fired off and I’m going to go in here I’m going to just hit any key and hold it down so hit the letter K and you’ll see it it fires off if I Let Go nothing else happens it’s basically as when you tap any key and it doesn’t matter if you just tap it quickly or hold it down it fires off that event just once all right now the next two key up and key down let’s comment this one out and let’s look at let’s look at Key up first so we’ll say on key up it’s the key up event and then I’m just going to copy this down say whoops on key up and key up okay so now what I’m going to do is again just just hit a key and hold it and nothing happens yet but when I release then that fires the key up event all right and that function gets called so when you release is when this is this event now let’s go ahead and do the key down so key down and I’ll just whoops that’s not what we want I want to copy this down and we’ll call this on key down key down okay now I’m going to choose a key I’ll just do the letter H and I’m going to hold it down now notice it fires off but it keeps firing off as I’m holding it down until I release and then it stops so that’s the difference between key press and key down key press is basically just it as if you were to tap it once where key down it’s going to keep going if you hold it down now there’s a couple properties on this event object where you can get the key that’s pressed because in many cases you’re going to need to know that let’s say you’re creating a game where you can hit the arrow keys and you can move something in different directions so obviously you need to know what what arrows which keys are being pressed or you might simply have an input field without a submit button and you want to know when they hit enter so that you can do something so there’s many cases where you’ll need to do this so what we’re going to do is first of all let me just put the comments in here so this there’s actually three we can use there’s key there’s key code and there’s code all right now key is probably the easiest however there are some older browsers that don’t support this um I think you you’d probably be fine using it but you might want to use another one in combination or instead of it but let’s just do a console log here of e dot key so I’ll just type in let’s say B so you can see it’s logging in the console whatever I’m typing and you could do whatever you want with this like we could say uh document Dot I’m not going to keep this but just to show you real quick if I select the H1 and then we could set the let’s say in our text equal to e dot key and now if I type in here b r a d it’s gonna it’s gonna replace it it’s not going to append it we could have it appended if we wanted to but it’s just going to replace with whatever I type all right so again just something kind of cool you can experiment with but let’s get rid of this and I just want to show you if you want to test for a certain key what you could do is you could just put this in an if statement and we could say if key equals let’s say enter capital E enter and then we want to do an alert and we’ll say you pressed you pressed enter all right now in this case if I hit enter it actually is going to submit the the form to the page however alerts are they’re blocking they’re blocking events so it will fire the alert before it actually tries to submit so if I hit enter you’ll see that I get the alert if I type anything else it doesn’t until I hit enter all right so that’s key now for key code it’s a little bit different it’s going to give you an actual number a key code so I’m going to paste this link in here and this is a link to a page that will give you the key codes so you can see like enter is 13 shift is 16. so every key on the keyboard has one of these codes these key codes so if I wanted to for instance check for enter I could say if and then say e Dot key code so if e key code is equal to the number 13 then we’ll just same thing we’ll just alert and say you pressed enter and I’m just going to comment this one out all right so if I save that I type in here and I hit enter you can see that’s another way we can test it and then we also have code so for this it’s going to look like let me just we’ll console log e dot code so if I hit like the letter F it says key f key D if I hit the number one we get digit one so of course if we wanted to check for that we could say if and let’s say we want to check for if we hit the number one so we could say equal to and then the string of Digit one and then we’ll just we’ll do a console log and say you pressed one so now if I hit in here if I go two three four but if I hit one then we get the console log all right now there’s also a repeat property and you’re gonna usually use this on the key down because what it does is it it lets your script know if you’re holding a key down or not all right so if you just tap a key it’s going to be false if you hold the key down then it’s going to be true so what we can do is let’s just do an if here and we’ll say if e dot repeat and that’s going to be true or false so we can just pass that in then we’ll console log and we’ll say you are holding down and then I’m just going to concatenate on that e dot key so now if I click in here and I just tap let’s say the letter L you’ll see that nothing happens in the console however if I if I hit and hold l we get you are holding down L because that repeat property is true as long as I’m holding a key down so you can really just tell like whatever whatever the user’s pressing as well as how they’re pressing it you can also test to see if they’re holding shift or control or alt so let’s come down here and I’m just going to console log these so these are properties we have shift key control key and ALT key so let’s console log and I’m just going to put the text shift and we’ll do shift colon and then I’m going to just concatenate on the shift so shift key property all right so now if I come over here if I just hit the letter D we get shift false if I hold shift and hit D we get shift true okay so that you can tell if they’re doing these combinations same thing with control and ALT so if we say um what is it Ctrl so control and then we also have alt which would be option on a Mac so this will be ALT key all right so come over here and I’ll do just hit L everything’s false if I do control L you can see control is true if I do option or alt L true so you can tell that the key combinations and you can you could do an if statement here as well and of course you could say if e Dot say e dot shift key and we want to check if let’s say e dot key is equal to K and then we’ll just do a console log here and say you hit shift plus k so now I’m going to come in here and I’m going to hold shift and hit K it says you hit shift plus k all right so those are keyboard events along with these different properties you can use to to figure out which key is actually being pressed all right guys so now we’re going to actually build a little project using the the key code information that we learned in the last video so this is actually a production application at toptel.com developer key code and it says press any key to get the JavaScript event key code info which is the stuff we looked at in the last video so I’m just going to hit a random key I’ll use the letter L and what it’s going to give us this 76 this is actually the event dot key code remember we have a number for every every key and then down here you can see what you get for event dot key which would be L you have event dot code which would be key L we’re not going to do these other things which you could because these are also on the event object but what I want to do is kind of recreate this application and just show the event dot key the event dot keycode and the event dot code all right now what you’ll have in the starter file is simply the HTML and CSS if I hit a key nothing’s going to happen right now because it’s just HTML and CSS now this is actually from my 50 projects in 50 days course however in the course we did it kind of the quick and dirty way where we just used in our HTML and then set these three basically these three divs okay I’m going to show you that way but I’m also going to show you a better cleaner more performant way where we actually create each of these key elements in the Dom and then we insert them and we’re going to be using a 4 in loop we’re going to be using an object we’re going to be you know doing stuff we’re going to use pretty much everything we’ve been talking about up to this point so I think it’s a good project for this point in time now if we go to the HTML you can see I just have everything hard coded right and there is some styling just some very basic styling here I didn’t want to go through the CSS or type out the CSS but just a background color on the body and then each of these boxes are going to be a div with the class of key so I have the border the background and then we have a small tag which is going to be each of these so if we look at our HTML each of those those titles are in small tags okay but what we want this to do is be dynamic so that this changes this changes and this changes based on whatever key we hit now if you want to pause the video and try this on your own I would encourage you to do that but it’s understandable if you know if you’re just learning this stuff you might not be able to do that just yet so and again I’m going to show you two ways of doing it the first way is is really simple but I would actually recommend the second way so let’s say I’m just going to call this method one of doing this and there’s so many different ways you could do it so we’re going to take what I’m going to do is just listen on the window for an event all right because I don’t want we’re not going to have a specific element where you push a key like we did in the last video with the input form as long as it’s on the window then we want to fire this off so let’s say window dot add event listener and we want to listen for a key down event and then I’m going to call a function actually for this one I’ll just put the function right in here and I’ll use an arrow function so we want to pass in our event object and then what I’m going to do is take the insert element this right here and pretty much just create all this HTML but with have having this Dynamic these three items here these should be all com they should come from those those key code properties so let’s uh I guess yeah we’ll just bring the insert in right here so let’s say insert equals document Dot and we’ll use we’ll just use get element by D and insert and then I’m simply going to take insert and just edit the inner HTML so I’m going to set that to some back text and then all we really have to do is bring in this stuff as a template so I’m going to just grab these three divs with the class of key and cut those and for now as far as when you just come first come to the page we’ll just have a message that says press any key to get the key code okay so when we come to this to the to the website it’ll just show us this all right and then I’m gonna just paste in those three divs here and you might just have to kind of format this a little bit to uh to look a little better so we’ll just push these over all right now we just want to replace these three so the first one is going to be the E dot key so let’s simply replace that with our syntax our dollar sign curly braces and just say e dot key and then we’ll come down here and replace this and make this Dynamic so this will be e Dot key code and then this one will be whoops that should be money sign this should be e dot code all right and that should actually do it and if I come over here and I hit let’s say the F key you see I get f for the the key property 70 for the key code and key f for the code if I hit W if I hit n if I hit enter if I hit the the digit one now the one thing that you want to look out for is with the space so with the space button the key is actually just an empty string or a space in the string so what we can do here is just say right in here we’ll say if the uh we’ll we’ll have a condition so we’ll say if this is equal to a space like that then let’s just have the word space else then we’ll show whatever the key is so now if we hit space now space will get put in there instead of just an empty string I shouldn’t say an empty string but a space all right so that’s kind of the easy quick and dirty way of doing it and there’s nothing wrong with this I’m I’m not like one of those sticklers that thinks everything has to be perfect this works just fine but I do want to show you an alternate way of doing it as well so let’s go ahead and just comment this out and then I’m going to come down here and we’ll say method two and this is going to show us not just we’re going to touch on a lot of things that we’ve talked about so far so again we’re going to add on the window object we’re going to add an event listener and we want to listen for our key down and then I’ll put this in a separate function let’s call it show key codes if you want to keep it in uh you know just a regular Anonymous function that’s fine oops we definitely don’t want those so let’s come up here and let’s say function and show key codes okay we want to pass in our event object and then we want to select the insert again so I’m just going to grab that okay so we have our insert that’s what we’re obviously where we want to insert these Keys into and then the way that I’m going to do this remember there’s so many ways to do the same thing but what I’m going to do is create an object kind of a map I could even use a JavaScript map but we haven’t gone over that yet so let’s say key codes set that to an object literal and then for the key I want to use you know e dot key e dot key code Etc but since there’s a DOT we have to if we want this to work as an object with key value pairs we have to put quotes around that okay because that’s that’s the key it’s the title the actual key is going to go in here so e dot key now we do want to test for space again so basically we can do this same thing that we did right here so I’ll just put that in there it’s just going to test to see if it’s a empty space if it is it’ll just replace it with a string space so next we want the key code property so for the for the title here we’ll just say key code make sure you put quotes around that and the value is going to be e dot key code which will be the actual value and then we also want e dot code the value for that is going to be e dot code so what we’ll do now is let’s just do a console log of key codes and see what that gives us so if I come over here and we open up our console and if I just type something in I’ll hit the letter F so now we’re going to get an object that has our key our key code and our code if I hit the enter and so any key it’s going to just give us this object now I want to actually Loop through this object and remember to do that we can use a 4 in Loop because the idea here is to Loop through them and create one of those divs but one of these divs for each of these all right so I did with the class of key for each of these we want to create that we want to insert the text node which will be the whatever the value is also will create a small tag and append that into the key and add a text node to small as well so we’re just we’re basically like it we’re building it up okay we’re building it from scratch rather than just replacing the HTML so to do that let’s say four and what we want to have in here is let’s say let key in key codes which is the name of the object and I want to start to build up our our elements so let’s say cons div and we’ll set that to document Dot and we want to create a new element so create element we want to create a div element okay and then let’s add the key class to that so we’ll say div dot class name and we’ll set that to key right now we also want a small element so I’m going to create that as well say small equals document Dot and then create element and that’s going to be a small tag all right now for the text for that we want to put in here I’m going to create a variable for let’s say key text okay so this is basically um uh let’s see it’s it’s it’s this right here so what we want to be in the small text okay so let’s say key text and set that to document Dot and we want to create a text node and then pass in here just key okay because remember when we say let’s key and key code that pertains to this and this is a little confusing because when you look at an object it’s a key value but these are we’re also looking at Key Properties so it is a little confusing you could call this something else if you want now we also want the text for the actual key code that comes from the event object so that will be the value right it’ll be this the value of the object this is the key this is the value so let’s call this one we’ll call this one value text and then what we want to pass in here to get the value we can say key codes and then use the index of the key right so we could say key codes and then in Brackets put any of these and it will give us the value and that’s going to go in here now we just want to append the text nodes to the elements so let’s take the small element and let’s say a pen child and we want to append into the small the key text which is like the title which is this right here okay then we want to put the actual value into the key div so let’s say div Dot a pen child and we’re going to add in here the value text all right and then we need to append the small element into the div element so let’s say div a pen child again and we want to pass in here small and then the last thing to do is to add the div to the Dom so we’re going to take that insert element and we’re going to append child and then we’re going to put the div in there all right so let’s try that I’m going to save come over here I’m going to hit just uh we’ll hit the letter k now a couple things one we don’t want this to show two if I hit another key it just adds to it right every time it’s just going to keep adding so what I’m going to do is just clear the inner HTML of insert before we do anything so we’ll say insert Dot in our HTML and we’ll set that to just nothing okay so now when I hit a key let’s say the letter L the the welcome message goes away also if I hit another one it replaces it okay because what we’re doing is clearing everything before we actually before we go on and do any of this all right now obviously this is much easier than doing this but here we created you know we looped through what we need the data here and then we just created a new div element for each one and then inserted it into the Dom so in my opinion this is a better way of doing it but again I’m not bashing this this way either alright so hopefully you enjoyed this little project and we’ll do more of these throughout the course as we go all right guys so now we’re going to look at input events and how you can get the values for a form input and just for this video I’ve added a couple additional inputs so we had the text field right here which is this input and then I added this select list so just for a priority like a shopping item priority and basically I just have an ID of priority input and each option has a value 0 1 2 3 and then I also just added a check box here so we want to be able to tell if this is checked or not now if you’re submitting a form to some kind of backend technology like like PHP or node.js you would probably have like an action in your form and then submit to a page and then to access the value from the back end you would usually use this name attribute so whatever you have assigned to that now in front-end JavaScript it’s a little bit different you would not have have it submit to a back end because you would basically take over in your JavaScript and and do whatever and in that case you need to be able to get these these inputs all right so let’s go into our script JS here and I’m going to bring in those inputs so let’s say item input and I’m just I’m going to use document dot get element by D that has an ID of item Dash input okay and then I’ll just copy this down a few times the next one has an ID of priority input that’s going to be the select list so we’ll call this priority input and then this one here let’s call it check box and that has an ID I believe of check blocks and then I’m also going to select the heading the shopping list heading just so we can use it to output something if we need so we’ll call this heading and that I don’t think it has an ID so I’m going to use Query selector on that one and just select the the H1 all right so let’s start off with the text input or the item input so we’ll say item input and I’m going to add an event listener onto it now there’s a few different types of events or different events that you can use to be able to get the value and work with this input so you may see key down used so I’ll say key down I’m going to create a function called on input and run that so let’s say function on input pass in our event object and then for now we’ll just console log input so now when I come in here and I start to type you’ll see it’s going to fire off every time I hit a key every time I type in the field all right now you can use key down but I would suggest not I’d suggest using the input event which in this case will do the same thing it fires off whenever we type in but you can also use this on other other input Fields like a select list like a key down isn’t going to work for a select list because you’re not pushing any key so I would suggest using input for your your most your input Fields now to get the value remember we have we have access to e dot Target which will give us the actual Target so if I start to type every time I hit a key it gives me the Target element which is the the input tag itself now of course we don’t want that we want the value that’s typed in so there’s a value property that we can access with e.target.value so now if I start to type in here you’ll see that it’ll give me whatever is in the the form field and it’s giving me the entire input it’s not just giving me the key that I press like we saw in in the LA or the video before a last in fact if I were to do e dot key here shouldn’t even yeah it gives me undefined because it’s an input event if I do like a key press event then I can get the individual keys but see how it’s not like accumulating it’s not appending on to the last because it’s just giving me the key with this e dot Target value it’s giving me whatever is in the input so that’s what you want to use in this case all right now before I move on to the next input let’s just we’ll set the heading just to show you we can take this heading and let’s take the text content and let’s bind whatever isn’t whatever is typed in that form which will make this Dynamic where we can type and it gets put into the heading in real time which is which is cool but not very useful I mean it might be useful in some cases um but yeah and obviously that’s only on your own machine and that’s only you know in your browser and if you reload that’s going to come back now the next thing let’s look at the priority input which is the select list so let’s change this to priority uh priority input and then change actually no I’ll just leave it like that uh oh I spelled those wrong okay so now if I select something here what’s going to happen is it’s going to fire this input event and this is going to run and I can still get the target dot value with this with the select list so if I choose 2 you’ll see now the H1 is actually outputting two three so whatever I choose and it’s always going to be the value obviously you know in the HTML it’s not going to be what you put in the middle here that’s just for the user to see this is the actual value that’s being chosen okay now you can use input for this but there’s also a and that’s probably what I would recommend but there’s also a change event that you can use on a select list as well which will do the same thing in this case okay but uh I would I I’d suggest using input but I’ll just leave it at change just so it’s there and you know you can come back to it now check boxes work a little differently instead of using e.target.value there’s actually an uh checked E dot Target dot checked so what I’m going to do is on the check box say check box and we’re going to listen for an event so let’s listen for um we’re going to use input here but I’m not going to do the on input I’m going to do on checked okay and then we’ll come over here and we’ll say function on checked pass in our event object and then I’m just going to console log here e dot Target Dot checked okay now when I select it you’ll see that it would get true if I unselect it then we get false so it’s as simple as that to get if the check box is checked or not so what we could do is we could take the let’s say heading and we’ll say text content and let’s say if the check box [Music] um how should we do this we could put this in a variable we could say caused is checked and set that to that value and then say if is checked then we’ll say checked else we’ll say not checked so let’s save that and then I’m going to go ahead and check it and now you’ll see the H1 changes to checked uncheck it we get not checked all right now there’s two other input events that I want to show you and that’s focus and blur which has to do with clicking in and activating the input and clicking out of it and unactivating so clicking in it is going to be focus and and clicking outside will be blur so let’s use this on the item input so what I’ll do is change Let’s do let’s do Focus and I’ll change this to say on Focus and we’ll actually just copy this down and let’s say on blur and let’s change that to blur and then we’ll come up here and create a function called on Focus and usually the reason that you would use this is like if you want to have a specific outline or something like that and I’ll just do a console log here first and say input is focused right so oh I have to create my own blur as well so we’ll say function on blur and we’ll say do a console log and say input input is not focused okay so if I click inside I get input as Focus if I click outside I get input is not focused but again usually what you would use this for is for styling so I could say item input and say Style and we’ll say outline style and let’s set that to solid okay and then we’ll do let’s copy that down and then in addition to outline style let’s do the outline with and we’ll set that to say one pixel and then we can also set the outline color and let’s set that to Green and then on blur what I’m going to do is just set the outline Style so outline style we’re going to set that to none all right so now if I come over here and I click in here now you see I get this green outline if I click out of it then it goes away we can change it to red okay so it’s it this is good for for just visual effects and UI um and this is what I mean earlier when I said you know you’re not going to use JavaScript just to change the style of a web page a static web page that doesn’t do anything but you use it to make your page Dynamic to have things happen to have styles change and borders at it and stuff like that um but yeah so that’s focus and blur now in the next video I want to look at form submission so when we how do we you know catch when we submit this because if I just submit it as is it actually submits it to the page which you could you know you could have it submit to like a backend PHP page or something like that but of course we’re dealing with front-end JavaScript so I’m going to show you how to prevent it from doing that and then doing what you want all right guys so now we’re going to look at form submission in the last video we looked at events on specific inputs so that you could do something when something in that input changed now we’re dealing with actually submitting the form now as I mentioned in the end of the last video if you’re working with a back-end technology like let’s say node.js or PHP or something like that then your form tag may have an action that submits to you know some file on your back end it could be node.js it could be PHP or whatever it might be but we’re dealing with front-end JavaScript so what we want to do is go into our script file and let’s uh let’s get the form and I think the form has an ID yeah it has an ID of item form so let’s say const and we’ll get our form we’ll set that to document Dot get element by D and it has an ID of item Dash form all right so now we just want to add an event listener to that form and we want to listen for the submit event and when that happens we’ll have a function called on submit fire off so let’s add that let’s say function on submit pass in our event object okay now I’m just going to do a console log here and we’ll say submit and I’m going to open up the console and by the way I add I still have the priority select list here because I want to use that as well but you’ll see if I put something in here and I click add item watch down here so notice how it just flashed submit real quick that’s because it did do the console log but then it’s submitted to the actual file if you don’t have an action attribute on your form where you’re submitting to some kind of backend then it’s going to submit to this the same page all right now to stop that you can just say e dot prevent default okay we looked at this a while back this prevents the default Behavior so now if I put something in here and I click add item it doesn’t submit to the file okay it just it stops and then it does whatever I want in the front-end JavaScript which in this case is just a console log now obviously if you’re doing this you’re going to want to get the values that are being submitted to the form so there’s actually a few ways to do that I’m going to show you the first way which I really already showed you and that’s to use the the value Target dot value but there’s also a form data object that you can use as well so to use the the value what I’ll do is I’ll put the basically we have the item and we have the priority so we have two Fields so I’m going to set item to document Dot and we’ll say get element by D and that has an ID of item Dash input and then we also want the priority input and I’ll just set this variable to priority Okay so to get the value now obviously like if I console log here let’s do item and priority whoops okay and if I put something in here milk one so it’s giving me the actual element which I don’t want so we can just add on to this dot value you could do it like this where you set the initial variable to value and then print it or you can set it this to the element and then when you’re ready to use it you can then say dot value so both of these will work if I put milk one and add we get milk in one so it’s up to you on how you how you want to do this I usually do it this way but of course there’s all kinds of different use different uh scenarios now this is where you know your front end JavaScript this is where you do you’ll do some validation and you you should have both front end and back end validation if you’re submitting to some kind of backend API you should do validation here but you should also do it on the server side so whatever route you’re submitting to you want to check your form fields and and stuff like that on the server as well I’m just going to add dot value here just to be consistent all right and then what I want to do is just check let’s say if and we’ll say if item we just want to make sure it’s filled so we’ll say if item equals nothing and then we also want to check we want to do an or here not an and because we want to check either or and priority if that is equal to in this case let’s say 0 because it has an initial value right if we look at the form here select priority we don’t want this to be selected and that has a value of zero so we want to just check for that and then if if either of those are true then let’s just alert and we’ll say let’s say please fill in all fields and then we’re just going to return from that okay so if I leave both empty and I click add item I get please fill in all Fields if I just do milk and I don’t select the priority I get the fill in all fields and notice it’s not console logging these because I returned from the function here so let’s choose a priority and make sure we have that filled in and now we don’t get the alert and we get the console log so this is just very very simple form validation now I also want to show you how to use the form data object so what I’m going to do is create another function and I’ll call this on submit to and let’s have this now submit to that function and we do we still want to prevent the default Behavior and then what I’ll do is initialize a form data variable and set that to new and then form data with a capital f okay and then we want to pass in our form which we have up here so it this is in the global scope meaning I can access it anywhere else so I’ll just pass in my form here and then what I want to do is just console log that form data and see and show you what that gives us all right so if we submit this with milk Priority One and if we look in here it might not work how you how you may think we don’t just have direct access to the values like an object of values but in the Prototype you can see that there’s a bunch of methods here so if you just want to get each individual entry then you can use the the get method so let’s do that let’s set let’s say const item and we’re going to set that to our form data variable and then there’s a get method and what we’ll do is pass in the item into here all right now this item is actually the name so if we look at the input here the name so if you if you’re using the form data object you want to make sure you have a name for these the name for this one is priority so the next one just copy that down and set that to priority because that’s the name that we assigned and this is a this is a newer way of doing this and getting values so console log item and priority so now I’m going to again just choose milk choose one and add item and now I’m getting those values now we can also get all of the entries using the entries method which which is a little weird but I’ll show you how that works so let’s say const entries and we’re going to set that to our form data variable and then dot entries with parentheses because it’s a method and I’m just going to comment these out and then let’s console log What entries gives us so again I’ll choose milk one and add and what we get is an iterator so this iterator basically it allows us to to Loop through it or to iterate through it so an easy way of doing this is to use a four of so we could come down here and say four and let’s say let entry so we’ll call each entry of and then the iterator which is entries okay and then in here if I console log entry comment this one out and select milk and one so what it gives me is for each input or each item it gives me an array that has both the name and the value so if I wanted to access the value I could do let’s say entry and one because this is just a simple array with a zero index and a one index so if I do that and I submit this again then I get milk and I get one and of course you can get the title as well I should say the name so item and priority so you can get either one of those and there’s a lot more to the form data object that we might get into later but I wanted to show you at least the the basics of that but in most cases for something simple like this I mean just using dot value is fine now in the next video we’re going to get into something that’s pretty important and that’s called event bubbling so in this video we’re going to talk about something that is pretty important when it comes to handling events and that’s event bubbling so when we add an event listener onto an element that event moves up the Dom tree and if it finds a parent element that has a listener for that event it’ll fire that as well so even if we click on the the button it’ll bubble all the way up to the document okay now it’s a little hard to understand with just me explaining it so let’s I’m going to show you how that works so let’s grab the the this button right here in the form so we’ll say const and we’ll just call this button and we’ll set document Dot query selector and I’ll just say form and then I want to grab the button in the form all right and then I want to add an event listener onto that button so add event listener and we’re going to listen for a click and then we’ll just put the function right in here and let’s do an alert and say the button was clicked all right so very simple if we click that we get button was clicked now what we’re going to do is bring in the parent to that button so if we go to our index.html and we look at that button so right here this is the button that we clicked and the parent to that would be this div which is the second it’s the second div in the form so we can Target it like that I’m going to come up here and I’ll say const and we’ll just call this div and set that to document Dot query selector and let’s say in the form we want the second div so we’ll say div and then nth Dash child and pass in two so that’ll give us that second div and then what I’m going to do is add an event listener onto that so click we want to click event and then let’s just do an alert here and this time we’ll say div div was clicked all right so now what I’m going to do is come over here to just to the right of the button and I’m going to click that because that’s the parent says div was clicked but now you’ll see if I click the button I get button was clicked if I click OK I get div was clicked so what’s happening here is we’re firing off this this click event here and then it’s bubbling up and then any any of its parents that have a click event listener it’s going to fire that as well okay now to show demonstrate this even further let’s bring in the form because the form is apparent to the the div so let’s say form and set that to document Dot query selector and we’ll get the form and then I’m going to do the same thing I’ll just change that to form and let’s say form was clicked so now if I click on the form I get forms clicked if I click on the button I get button was clicked it’s going to Bubble Up div was clicked it’s going to Bubble Up form was clicked okay so we can even go a step further and say document.body and add an event listener onto that and say click and then we’ll say let’s do uh alert and say body was clicked so now if I click on the button we get button was clicked div was clicked form was clicked body was clicked so this pertains to this diagram right here where we click the button and that event is going to Bubble Up through all of its parents and anything that has a click event on it that will also get fired off now there might be cases where you don’t want this to happen because it will just kind of mess your application up so that’s where the stop propagation method comes in and that’s part of the event object so if we go back up to where we have our button let’s pass in our event object here and I’m just going to go after the alert and say e dot stop propagation okay so now if I come over here and I click the button we get button was clicked and then nothing happens after that okay so event bubbling is is really not that difficult to understand I know it does intimidate a lot of people that are getting started with with JavaScript but it’s just that it just bubbles up and if you have another click event on a parent that’s going to fire off unless you stop propagation now you should only call stock propagation if you have a reason for it for instance if we actually had a parent and child with that with the same event listener and don’t just call it for the hell of it and then there’s also a method called stop immediate propagation and this is used if you have multiple handlers on a single event and you want to stop the event for all of them but yeah so that’s event bubbling now in the next video I want to talk about something called event delegation all right so we’ve talked about events quite a bit and we know how to add an event listener onto a single element but what about when there’s multiple elements and a good example is for these list items if you want to delete these we have multiple delete buttons where we would want to add an event listener to now there’s a few ways we can do this we could basically select all of the LI tags or all of the buttons whatever it is we want to click on and then add an event listener for every single one which isn’t really efficient so this is where event delegation comes into play which is a a powerful event handling pattern so so I’m going to show you the the first way which is to basically just add an event listener on to everyone so let’s do that by selecting the list items and we’re going to say document we want to use Query selector all because we’re selecting all of the all of the LI tags all right and then what we can do is we can list through our Loop through the list items and say for each item and then just to show you if I console log here um we’re actually going to want to well no let’s add the list let’s add the event listener first so I’ll say for each item let’s add an event listener for click and then we’ll have our function here and I’m going to just console log e Dot Target so if I click on these you’ll see it’ll give me whatever list item I’m clicking on so now I can take that Target and I can remove whatever I whatever that element is whatever I’m clicking on so I can say e dot Target dot remove and we learned about the remove method a couple sections back so now if I click on let’s say orange juice goes away click on milk Oreos apples and of course this is just in the Dom it’s just in the in our browser if I reload that all comes back that’s because we’re not persisting that we’re not persisting the data or persisting those actions to any database or anything like that all right now as I said this isn’t really efficient especially if you have a ton of of elements that you’re putting a listener on instead we can use event delegation to basically add just a single event listener onto the parent and then Target whichever one we want to delete so let me just show you what that looks like so we’re going to select the parent which is the UL so let’s say document Dot query selector and we’re going to select the UL and I’m just going to comment this this out for now and we want to put the event listener on the parent so list dot add event listener and listen for click and then we’ll have a function all right so now I’m going to go ahead and just console log here and then I want to log e dot Target so I’m going to come in here and click and notice it’s still giving me the list item right I have the event listener on the UL so even if I click Like right here then it gives me the UL if I’m not clicking on the list item so what I can do is just Target the list item that I’m clicking on this e dot Target and remember Target is going to give you what you click on current Target is going to give you what the uh what the event listener is on so if I do current if we say e dot current Target and I click on the list item it’s still going to give me the UL so you want to make sure that you’re dealing with Target and we what we can do is just test and say if e dot Target dot tag name or class or whatever it is that you want to check if that is equal to in this case Li then we can just take that e dot Target which is what we click on and we can remove it from the Dom so now if I click on any one of these it just deletes them and now instead of adding multiple event listeners I’m just simply adding one and then I’m testing whatever it is I’m clicking on and then deleting that and and of course you’re not limited to just deleting if I wanted to let’s say let’s say instead of a click we do a mouse over and again we just want to check to make sure it’s a list item and then instead of removing it let’s change the style dot color and we’ll set that to Red so now if I come over here and I hover over a list item you see it will only it’ll change the ones that I hover over to red all right so that’s how you want to handle adding an event listener onto multiple elements is using event delegation now in this case we just use the list item so if I click anywhere it deletes when we actually build our project which is very soon we’re going to have to Target the button which is going to be a little bit more difficult because we have to kind of navigate to the child to the button and then there’s an icon in the button so it’ll be a little more difficult but it’ll it’ll be fun and we’ll you’ll learn quite a bit going through this project in the next video though I want to talk a little bit about some of the the events that we can use on the window and about just the window object in general all right so the window object we’ve we’ve looked at a few times and I think it was the execution context section where I showed you that that’s the first thing the execution context does is it loads This Global window object that has a ton of properties and methods and apis and also events now the first events that I want to talk about are page loading events on this window object so you’ll notice that in the HTML for this section or for this lesson I have the script tag in the head and this was something that was very common practice back in like the 2000s so I just want to show you if we if we keep the script tag in the head and then we select let’s say query selector and all I have on this page is just an H1 and and some paragraphs so I’m going to select the H1 and I’ll set the text content to hello world and I’m going to save so you’ll notice that we get an error in the console it says cannot set properties of null setting text content so what it’s saying is that this is null and the reason for that is when we put our script tag in the head like this where we’re do we’re running our JavaScript before the page is loaded and before the Dom is loaded so it doesn’t know what this is yet so a common practice would be to use the load event so we could say on window we could say dot add actually I’ll show you the the on load which was what we saw a lot of back then so window dot on load and this was kind of a hack to do window on load set it to function and then put our code in there so you’ll see if I save now the H1 is replaced and we don’t get an error anymore so by using on load we’re waiting for the entire page to load and that includes resources like images and stuff like that and of course we could use add event listener which wasn’t around back then what I’m talking about but you can use this with load as well so we’ll just put a function in here and let’s just copy that and paste that in I’ll comment that out and you’ll see that just get rid of that semicolon that does the same thing now there’s also an event called Dom content loaded so what I’m going to do is copy this and then paste it in I’m going to change load to Dom all caps and then content loaded and then I’ll save and we get the same result now the difference between load and Dom content loaded is load waits for the the entire page to load including all resources such as images where Dom content loaded runs as soon as the Dom is parsed and loaded so if I were to run both of these let’s actually you know what we’ll do is uh let’s just replace this with a console log so I’m going to say console log and we’ll say page loaded and then I’m going to replace this one with a console log and we’ll say here Dom uh what happened here let’s say Dom loaded and notice that the Dom gets loaded first obviously because the page load includes the Dom and everything else any obviously there’s no images here but any other resources that need to be loaded now if I were to do a console log in the global scope down here and we’ll just say run me if I save that that gets run before either of these because we’re not in any of these events where we’re waiting for the page to load which is fine when the script is down you know under the page down above the ending body tag but if you have to access any Dom elements from the global scope then you’re going to get an error if the script tag is in the head now the exception to this is if you use the fairly new defer attribute so if I come to the script that’s in the head here and then I add on to it defer like that and I save and then let’s come over here and we’ll take I will not take let’s just go in back into the global scope here and say document and we’ll select the H1 and then let’s set the inner text and set that to hello world and if I save that you’ll notice that it works okay so I’m not getting the error even though my script is in the head but I use this defer attribute which basically will do just that it will defer the JavaScript code from running until it can run until the pages are the Dom is loaded so this is this is pretty new I don’t know when exactly this was available but if you want to do it this way and put your scripts in the head that’s absolutely fine just make sure you use defer I still prefer to keep my my scripts down above the ending body tag but from this point on if you want to use defer and put them in the head that’s fine now there’s just a couple other events that I want to show you that we can use on the windows so let’s say window dot add event listener and we can listen for a resize okay so there’s a resize event and what I’m going to do here is I’m gonna actually take this and move this into here but I’m going to set the the text to show the size of the window so we’ll put some backticks in here and we’ll say resized resized two and we can remember we can get the inner width and the inner height on the window object so let’s say window Dot in our width and then we’ll also put the window Dot inner height so I’m going to save that and now if I resize it’s going to change the H1 to show the the inner width and inner height and you’ll see it’s just it keeps changing because that event just fires off every time the browser is resized also it stayed at 276 because we didn’t change the height if I move this console then that’s going to change the height also listen for a scroll event so this can be helpful for certain UI effects that you want to create so I’m going to add an event listener onto the window and I’m going to listen for scroll and of course you could do window dot on scroll equals a function if you want to do it like that and then let’s create a function and what I’m going to do is console log and we’ll use some back ticks and we’ll say scrolled and let’s add in here because on the window object we have access to scroll X which is the position when you’re you know scrolling horizontal and then we also have the um scroll y so window Dot scroll Y and now if I scroll down you’ll see the the x is going to stay at zero because I’m not scrolling horizontal at all but the more I scroll down you’ll see the higher that that scroll X I’m sorry scroll y value gets and we could do some cool stuff here like if you have a navigation bar at the top and you want to have it be like translucent or something when you start to scroll you can just test where that scroll y value is so in fact we could do something like this we could say if the window Dot scroll Y is let’s say greater than 70. then let’s take the document body and on the style we’ll take the color or let’s do background so background color and we’ll set that to Black and then we’ll set the color to white the text color change that to color all right if I do that and then I start to scroll as soon as it hits 70 the background turns black now it’s going to stay black because I didn’t specify anything else but I could put an else on here and then we could take this and then just change this back to White and change the text Back to Black so now if I come down I hit 70 it turns black I go back up it turns White so this is the start of learning how to create really cool Dynamic functionality or dynamic effects within your UI so what else we also have focus in blur and just to give you a quick example of that we’ll say window dot add event listener and just like you have on inputs we focus in blur it’s just when you click in and when you click out so let’s just mess around with this for a second and let’s take document Dot query selector and we’ll select the paragraph actually let’s select all paragraphs so we’ll say all and then let’s look through those so we’ll say four each P so for each paragraph then let’s say p dot Style dot color and set that to Blue and then let’s put one for blur so on blur which is when you click out of the window then we’ll set it to bla Back to Black so now if I click in here you can see the scroll thing’s still working too but you can see that they’re all it’s all blue if I click outside of the window so anywhere else then it turns black Back to Black and there’s other events on the window object as well if you want to check the mdn docs of course you can do that but yeah so that those are window events and also the the page loading events

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

  • JavaScript Programming: From Fundamentals to Practical Applications

    JavaScript Programming: From Fundamentals to Practical Applications

    This YouTube transcript presents a comprehensive JavaScript course designed for beginners. The course covers fundamental concepts such as variables, data types, operators, control flow, functions, objects, classes, and the Document Object Model (DOM). It emphasizes practical application through real-world projects like a notes app, quiz app, and e-commerce product page. The transcript also includes explanations of JavaScript scope, event handling, and advanced topics like constructor functions and prototypes. Finally, there are instructions for building applications like a digital clock and a form validation project.

    JavaScript Fundamentals Study Guide

    Quiz

    Instructions: Answer the following questions in 2-3 sentences each.

    1. What is JavaScript, and what are two common uses for it in web development?
    2. Describe three different ways you can embed JavaScript code in an HTML file.
    3. Explain the difference between the var, let, and const keywords when declaring variables in JavaScript.
    4. Define “scope” in JavaScript, and name the three types of scope.
    5. Name four of the seven primitive data types in JavaScript and give an example of each.
    6. Explain the difference between the == and === operators in JavaScript.
    7. Describe the purpose of control flow statements in JavaScript and give one example of a conditional statement.
    8. Explain the difference between the break and continue statements within a JavaScript loop.
    9. What is a JavaScript function, and how is it defined and called?
    10. What is a JavaScript object, and how do you access properties and methods within it?

    Quiz Answer Key

    1. JavaScript is a scripting language used to create interactive and dynamic websites. It’s commonly used for front-end web development to add interactivity, such as button clicks and form validation, and also used in back-end web development with Node.js.
    2. JavaScript code can be embedded in an HTML file in the <head> tag within <script> tags, within the <body> tag, or through an external JavaScript file linked using the src attribute in the <script> tag.
    3. var is the oldest and most common way to declare variables, with function scope. let is a newer keyword that declares block-scoped variables, meaning they are only visible within the block in which they are declared. const is used to declare constants, which are variables that cannot be reassigned once they are declared.
    4. Scope refers to the visibility of variables and functions within a program. There are three types of scope in JavaScript: global scope, function scope, and block scope.
    5. Four primitive data types in JavaScript are: string (e.g., “Hello World”), number (e.g., 3.14), boolean (e.g., true), and undefined (a variable that has been declared but not assigned a value).
    6. The == operator checks for equality of values after type coercion, meaning it may convert the types of the operands before comparison. The === operator checks for strict equality, meaning it compares both the value and the type of the operands without type coercion.
    7. Control flow statements are used to control the order in which code is executed in a JavaScript program. An example of a conditional statement is the if statement, which executes a block of code only if a specified condition is true.
    8. The break statement is used to terminate a loop immediately, while the continue statement skips the current iteration of the loop and proceeds to the next iteration.
    9. A JavaScript function is a reusable block of code that performs a specific task. It’s defined using the function keyword followed by the function name, parameters (optional), and the code block enclosed in curly braces. It’s called by using the function name followed by parentheses.
    10. A JavaScript object is a non-primitive data type that stores a collection of data in key-value pairs. You can access properties using dot notation (e.g., object.property) or bracket notation (e.g., object[“property”]). Methods are functions associated with the object and are accessed the same way as properties (e.g. object.method()).

    Essay Questions

    1. Discuss the importance of understanding variable scope in JavaScript and how different types of scope can affect the behavior of your code. Provide examples to illustrate your points.
    2. Explain the concept of data types in JavaScript, differentiating between primitive and reference data types. How does an understanding of data types contribute to writing robust and error-free code?
    3. Describe the various operators available in JavaScript, categorizing them by function (arithmetic, assignment, comparison, logical). Explain how operator precedence and associativity impact the evaluation of expressions.
    4. Compare and contrast the different looping structures available in JavaScript (for, while, do…while). Provide scenarios where each type of loop would be most appropriate and justify your choices.
    5. Explain the concept of DOM (Document Object Model). Discuss DOM manipulation techniques using JavaScript. What is the importance of DOM manipulation in web development?

    Glossary of Key Terms

    • JavaScript: A scripting language primarily used to create interactive and dynamic websites.
    • 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.
    • Variable: A storage location that holds a value.
    • Keyword: A reserved word that has a special meaning in the JavaScript language.
    • Scope: The visibility of variables and functions in a JavaScript program.
    • Global Scope: Variables declared outside any function or block, accessible from anywhere in the script.
    • Function Scope: Variables declared inside a function, only accessible within that function.
    • Block Scope: Variables declared inside a block (e.g., within an if statement or loop), only accessible within that block (introduced with let and const).
    • Data Type: The type of value that a variable can hold (e.g., string, number, boolean).
    • Primitive Data Type: Basic data types that represent a single value (string, number, boolean, null, undefined, symbol, bigInt).
    • String: A sequence of characters enclosed in single or double quotes.
    • Number: Represents numeric values, including integers and floating-point numbers.
    • Boolean: A data type with two possible values: true or false.
    • Undefined: A value assigned to a variable that has been declared but not yet assigned a value.
    • Operator: A symbol that performs an operation on one or more operands.
    • Arithmetic Operators: Operators used to perform mathematical calculations (e.g., +, -, *, /).
    • Assignment Operators: Operators used to assign values to variables (e.g., =, +=, -=).
    • Comparison Operators: Operators used to compare two values (e.g., ==, ===, >, <).
    • Logical Operators: Operators used to perform logical operations (e.g., &&, ||, !).
    • Operator Precedence: The order in which operators are evaluated in an expression.
    • Operator Associativity: The direction in which operators of the same precedence are evaluated (left-to-right or right-to-left).
    • Control Flow Statements: Statements that control the order in which code is executed (e.g., if, else, switch, for, while).
    • Conditional Statement: A statement that executes different code based on a condition (e.g., if, else if, else).
    • Loop: A control flow statement that repeats a block of code multiple times (e.g., for, while, do…while).
    • Function: A reusable block of code that performs a specific task.
    • Parameter: A variable declared in a function definition that receives a value when the function is called.
    • Argument: The actual value passed to a function when it is called.
    • Return Statement: A statement that ends the execution of a function and returns a value (optional).
    • Object: A collection of properties (key-value pairs).
    • Property: A key-value pair in an object, where the key is a string (or symbol) and the value can be any data type.
    • Method: A function that is a property of an object.
    • this Keyword: A keyword that refers to the current object in a method.
    • Constructor Function: A function used to create objects.
    • new Keyword: An operator used to create an instance of an object from a constructor function.
    • class Keyword: A keyword used to define a class, which is a blueprint for creating objects (introduced in ES6).
    • Getter: A special method in JavaScript that is called when a property is accessed, used to retrieve property values.
    • Setter: A special method in JavaScript that is called when a property is modified, used to set property values.
    • Event: An action that occurs in the web browser, such as a click, mouseover, or keypress.
    • Event Listener: A function that is executed when a specific event occurs.
    • Element: An individual component of an HTML document.
    • Node: A generic term for any type of object in the DOM tree (e.g., element, text, comment).
    • Parent Node: The node directly above another node in the DOM tree.
    • Child Node: A node directly below another node in the DOM tree.
    • Sibling Node: Nodes that share the same parent node in the DOM tree.
    • document.getElementById(): A DOM method to select a specific element.
    • document.querySelector(): A DOM method to select an element using CSS selectors.
    • document.querySelectorAll(): A DOM method to select a set of elements using CSS selectors.
    • element.parentNode: Returns parent element of specified node.
    • element.children: Returns HTMLCollection of an element’s child elements.
    • element.innerHTML: Sets or returns the content of an element.
    • element.textContent: Sets or returns the text content of an element.
    • element.setAttribute(): Sets the value of an attribute on the specified element.
    • element.classList: Returns the class names of an element.
    • Event Bubbling: Is an event flow model in which event flows from the most specific element to the least specific.
    • Event Capturing: Is an event flow model in which event flows from the least specific element to the most specific.

    JavaScript Tutorial: A Beginner’s Guide

    Okay, here’s a detailed briefing document summarizing the main themes and important ideas from the provided JavaScript tutorial excerpts.

    Briefing Document: JavaScript Tutorial Overview

    I. Main Themes

    • Introduction to JavaScript: The core of the excerpts focuses on introducing JavaScript as a scripting language essential for creating interactive and dynamic websites. It emphasizes its widespread use and relevance in modern web development.
    • Beginner-Friendly Approach: The tutorial is explicitly designed for individuals with no prior coding experience. It promises clear explanations, practical examples, and complete notes to facilitate learning.
    • Practical Application and Projects: A key element is the emphasis on learning by doing. The tutorial promises real-world projects (online notes app, quiz app, etc.) to solidify understanding.
    • Fundamental Concepts: The tutorial covers essential JavaScript concepts, including variables, data types, operators, control flow statements, functions, objects, and DOM manipulation.
    • Modern JavaScript Features: The excerpts touch on newer JavaScript features introduced in ES6, such as the let keyword and default parameters.
    • Emphasis on DOM (Document Object Model): A significant portion is dedicated to understanding and manipulating the DOM, enabling dynamic interaction with web page elements.
    • Event Handling: An introduction to JavaScript events, detailing how to make web pages interactive.
    • Project-Based Learning: Several mini-projects are outlined to provide hands-on experience in applying JavaScript concepts.

    II. Important Ideas and Facts

    • What is JavaScript?“JavaScript is a scripting language that is used to create interactive and dynamic websites.”
    • Interactive websites: enable user actions like “button click, submit a form, write comments, and live chat.”
    • Dynamic websites: change content/layout like “sliding effect, e-commerce website and quiz website.”
    • Why Learn JavaScript?“JavaScript is the most popular programming language in the world.”
    • Used by major websites: “Google, Facebook, Twitter, Amazon, Netflix.”
    • Vast ecosystem: “tons of Frameworks and libraries to reduce your time to create websites and mobile apps some of the popular Frameworks are react angular and vuejs.”
    • Career opportunities: “if you learn JavaScript it opens a lot of job opportunities in the software development Industries.”
    • Uses of JavaScript:Beyond front-end: “not only limited to front-end web development it is also used in backend web development mobile app development desktop app development game development and API creation.”
    • Setting Up a Development Environment:Requires a web browser (e.g., Google Chrome) and a code editor (e.g., Visual Studio Code).
    • Adding JavaScript to HTML:Inline: Within <script> tags in the <head> or <body>.
    • External: Using <script src=”script.js”></script>, linking to an external .js file.
    • “There are multiple options to display the output of JavaScript on the web page or browser.”
    • alert(“message”): Displays an alert box.
    • document.write(“message”): Writes directly to the HTML document.
    • console.log(“message”): Logs messages to the browser’s console.
    • Variables:“Variables are used to store data.”
    • Declaration: var, let, const.
    • var: Oldest, most common way.
    • let: Block-scoped (ES6).
    • const: Declares constants (cannot be reassigned).
    • Naming: Must begin with “alphabet dollar sign or underscore”.
    • Case-sensitive: “JavaScript is case sensitive”.
    • Scope:Global: Accessible from anywhere.
    • “variables and functions declared in the global scope are visible from anywhere in the program”
    • Function: Only accessible within the function.
    • “variables and functions declared in a functions scope are only ual within that function”
    • Block: Only accessible within the block (e.g., within an if statement).
    • “variables and functions declared in a block scope are only visible within that block”
    • Data Types:Primitive: String, Number, Boolean, Null, Undefined, BigInt, Symbol.
    • String: “a string is a sequence of zero or more characters”
    • Number: represents integer and floating point numbers
    • Boolean: true or false values
    • Reference: Object, Array, Function.
    • Object: “a non-primitive data type that allows you to store multiple collections of data”
    • Array: “arrays are a type of object that stores a collection of values”
    • Function: “functions are a type of object that can be used to execute code”
    • Dynamic Typing: “JavaScript is a dynamically typed language so we can store different data type in the same variable.”
    • Operators:Arithmetic: +, -, *, /, % (modulus), ** (exponentiation).
    • Assignment: =, +=, -=, *=, /=, %=, **=.
    • Increment/Decrement: ++, — (prefix and postfix).
    • Comparison: <, >, <=, >=, == (equality), != (inequality), === (strict equality), !== (strict inequality).
    • Logical: && (AND), || (OR), ! (NOT).
    • String: + (concatenation).
    • Operator Precedence and Associativity:Precedence: Determines the order of operations.
    • Associativity: Determines the order when operators have the same precedence (left-to-right or right-to-left).
    • Control Flow Statements:Conditional: if, else if, else, switch, ternary operator (condition ? valueIfTrue : valueIfFalse).
    • Loops: for, while, do…while.
    • break: Terminates a loop.
    • continue: Skips the current iteration.
    • Functions:“a block of code that performs the specific task.”
    • Declaration: function functionName(parameters) { … }.
    • Parameters and Arguments: Parameters are variables in the function definition; arguments are the values passed when calling the function.
    • Default Parameters: function myFunction(param1 = defaultValue) { … }.
    • return: Returns a value from the function.
    • Recursive Functions: Functions that call themselves.
    • Anonymous Functions: Functions without a name.
    • Callback Functions: Functions passed as arguments to other functions.
    • Objects:“a non-primitive data type that allows you to store multiple collections of data”
    • Key-value pairs: const myObject = { key1: value1, key2: value2 };.
    • Accessing properties: objectName.propertyName or objectName[“propertyName”].
    • Methods: Functions within objects.
    • this keyword: Refers to the current object.
    • Getters and Setters: Special methods to control property access and modification.
    • Classes:A blueprint for creating objects.
    • constructor: A special method to initialize object properties.
    • Methods: Functions within classes.
    • Inheritance: Creating new classes based on existing ones (using extends).
    • Private methods: A method inside of the class that can not be accessed from outside the class.
    • Static methods: can be accessed without creating an object of the class
    • DOM (Document Object Model):Represents the structure of an HTML document as a tree.
    • Nodes: Elements, text, attributes, etc.
    • Traversing: Moving through the DOM tree (parent, children, siblings).
    • parentNode: Returns the parent element of a node.
    • firstChild, lastChild: First and last child nodes.
    • childNodes: All child nodes.
    • nextElementSibling, previousElementSibling: Next and previous sibling elements.
    • Selecting Elements:
    • document.getElementById(“id”): Selects an element by its ID.
    • document.getElementsByClassName(“class”): Selects elements by class name (returns an HTMLCollection).
    • document.getElementsByTagName(“tag”): Selects elements by tag name (returns an HTMLCollection).
    • document.querySelector(“selector”): Selects the first element matching a CSS selector.
    • document.querySelectorAll(“selector”): Selects all elements matching a CSS selector (returns a NodeList).
    • Manipulating Elements:
    • document.createElement(“tag”): Creates a new HTML element.
    • element.appendChild(newNode): Adds a node as a child to an element.
    • element.textContent = “text”: Sets the text content of an element.
    • element.innerHTML = “html”: Sets the HTML content of an element.
    • element.setAttribute(“attribute”, “value”): Sets the value of an attribute.
    • element.removeAttribute(“attribute”): Removes an attribute.
    • element.classList: For adding, removing, and toggling CSS classes.
    • Adding and Removing elements:
    • element.insertAdjacentHTML(): A method to add HTML adjacent to an element.
    • replaceChild(): replaces a child element with a new one.
    • cloneNode(): clones a node.
    • removeChild(): removes a child element of a node.
    • insertBefore(): insert a new node before an existing node.
    • Attributes:
    • “The ID is the attribute name username is the attribute value”
    • to get the attributes of any HTML element use javaScript.
    • hasAttribute(): used to check whether an element has a specified attribute or not.
    • getAttribute(): method use to get the value of specified attribute.
    • setAttribute(): set the attribute.
    • removeAttribute(): remove the attribute.
    • Events:Actions that occur in the browser (e.g., click, mouseover, load).
    • Event bubbling: Event flow from the most specific element to the least.
    • Event capturing: Starts from the least specific element.

    III. Examples of Projects Mentioned

    • Online Notes App
    • Quiz App
    • Form Validation
    • Image Slider
    • Digital Clock
    • E-commerce Product Page
    • To-Do List App
    • Weather App
    • Calculator
    • Image Gallery

    IV. Conclusion

    The provided excerpts outline a comprehensive JavaScript tutorial suitable for beginners. It covers fundamental concepts, practical application through projects, and introduces modern JavaScript features. The emphasis on DOM manipulation and event handling highlights the tutorial’s focus on building interactive web experiences. By following this course, individuals with no prior programming experience can become proficient in JavaScript and be able to develop real-world applications.

    JavaScript FAQs: A Quick Reference

    Frequently Asked Questions about JavaScript

    1. What is JavaScript and what are its primary uses?

    JavaScript is a scripting language primarily used to create interactive and dynamic websites. It enables user actions like button clicks, form submissions, live chats, and website content or layout changes such as sliding effects, e-commerce functionalities, and quizzes. It can be used in front-end web development, back-end web development, mobile app development, desktop app development, game development, and API creation.

    2. Why should I learn JavaScript?

    JavaScript is the most popular programming language globally, used by almost all popular websites like Google, Facebook, Twitter, Amazon, and Netflix. It has numerous frameworks and libraries like React, Angular, and Vue.js, which help reduce development time. Learning JavaScript opens many job opportunities in the software development industry.

    3. How can I get started with writing JavaScript code?

    To start writing JavaScript, you need a web browser (like Google Chrome) and a code editor (like Visual Studio Code). You can add JavaScript code directly within the HTML file using the <script> tag in the <head> or <body>, or you can link an external JavaScript file using <script src=”script.js”></script>.

    4. What are variables in JavaScript and how do I declare them?

    Variables are used to store data. In JavaScript, you declare variables using the var, let, or const keywords. For example: var x = 30;, let x = 10;, or const a = 4;. var is the oldest and most common way, let is a newer keyword introduced in ES6 for block-scoped variables, and const is used for variables that should not be reassigned. Variable names must begin with an alphabet, dollar sign ($), or underscore (_).

    5. What is scope in JavaScript and what are the different types?

    Scope refers to the visibility of variables and functions within a program. There are three types of scope in JavaScript:

    • Global scope: Variables and functions declared in the global scope are visible from anywhere in the program.
    • Function scope: Variables and functions declared within a function are only visible within that function.
    • Block scope: Variables and functions declared within a block of code (enclosed in curly braces) are only visible within that block (using let or const).

    6. What are the different data types in JavaScript?

    JavaScript has two main categories of data types:

    • Primitive data types: These include string, number, boolean, null, undefined, bigint, and symbol.
    • Reference data types: These include object, array, and function.

    JavaScript is a dynamically typed language, allowing you to store different data types in the same variable during its lifecycle.

    7. What are operators in JavaScript and what are some common types?

    Operators are symbols used to perform operations on operands (values and variables). Common types include:

    • Arithmetic operators: Used for mathematical operations (e.g., +, -, *, /, %).
    • Assignment operators: Used to assign values to variables (e.g., =, +=, -=).
    • Comparison operators: Used to compare two values (e.g., ==, ===, !=, >, <). They return Boolean values.
    • Logical operators: Used to perform logical operations (e.g., && (AND), || (OR), ! (NOT)).
    • String operators: Used to concatenate strings (e.g., +).

    8. What are control flow statements in JavaScript and how are they used?

    Control flow statements are used to control the flow of execution in a JavaScript program. There are three main types:

    • Conditional statements: (e.g., if, else if, else, switch) used to execute different code based on different conditions.
    • Loops: (e.g., for, while, do…while) used to repeat a block of code.
    • try…catch statements: Used to handle errors.

    9. What are functions in JavaScript and how are they used?

    Functions are reusable blocks of code that perform specific tasks. You can define a function using the function keyword, followed by the function name, parameters (optional), and the function body. Functions can return values using the return statement. Parameters act as placeholders that receive argument values passed during the function call.

    10. How do parameters and arguments work in Javascript functions?

    Parameters are declared in the function definition, while arguments are the actual values passed to the function when it’s called. You can also use default parameters, which provide a default value if an argument is not provided when calling the function. JavaScript functions can be declared without names, also known as anonymous functions and can call upon themselves, known as recursion.

    11. What are objects in JavaScript and how do I work with them?

    Objects are non-primitive data types that store collections of data in key-value pairs. You can create objects using curly braces {}. Access properties using dot notation (e.g., object.property) or bracket notation (e.g., object[‘property’]). You can add, modify, and delete properties of an object. Objects can contain other objects, which are called nested objects, and methods.

    12. How do I define and use methods within JavaScript objects?

    Methods are functions that are properties of an object. You can define methods within an object using function expressions or by directly assigning a function to a property. You can call object methods using dot notation followed by parentheses (e.g., object.method()). To access other properties of the object within a method, you can use the this keyword.

    13. What is the DOM (Document Object Model) and how do I use it to manipulate web pages?

    The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. It allows JavaScript to dynamically access and update the content, structure, and style of web pages. You can select elements using methods like getElementById, getElementsByClassName, getElementsByTagName, querySelector, and querySelectorAll. You can traverse the DOM to navigate between parent, child, and sibling elements. You can manipulate elements by creating new elements, appending or inserting them, modifying content and attributes, and removing elements.

    14. How do I handle events in JavaScript?

    Events are actions that occur in the web browser (e.g., clicks, mouse movements, page loads). You can handle events using event listeners, which are functions that are executed when a specific event occurs. The two event models are event bubbling (event flows from the most specific element to the least) and event capturing (event flows from the least specific element to the most).

    15. What are classes in JavaScript and how do I use them?

    Classes are a template for creating objects. They are a way to organize and structure your code using object-oriented programming principles. A constructor is a special method within a class that is called when a new object is created from the class. The new keyword is used to create an instance of a class. Getters and setters are special methods that allow you to control how properties are accessed and modified. Using the # prefix indicates that the method is private. Static methods and properties are associated with the class itself, rather than with individual instances of the class. This means that you can access them directly using the class name without having to create an object.

    JavaScript Fundamentals: Variables, Data Types, and DOM Manipulation

    JavaScript is a scripting language utilized to create dynamic and interactive websites. A dynamic website can alter its content and layout, while an interactive website enables user actions like button clicks or form submissions.

    Key aspects of JavaScript covered in the sources include:

    • Variables and Scope Variables are used to store data and are declared using keywords like var, let, and const. The let keyword declares block-scoped variables, visible only within their defined block, while const declares variables that cannot be reassigned. JavaScript recognizes three types of scope: global, function, and block scope.
    • Data Types JavaScript divides data types into primitive and reference types. Primitive data types include string, number, boolean, null, undefined, bigint, and symbol. Reference data types include object, array, and function. JavaScript is a dynamically typed language, allowing variables to store different data types.
    • Operators Operators are symbols that perform operations on operands (values and variables). Types include arithmetic, assignment, comparison, logical, and string operators. Operator precedence determines the order in which operators are processed.
    • Control Flow Statements These statements manage the execution flow in a JavaScript program, enabling decisions, loops, and error handling. Common conditional statements are if, else if, and else. Loops include for, while, and do while loops. The break statement exits a loop, and the continue statement skips the current iteration.
    • Functions Functions are reusable code blocks that perform specific tasks. They are defined using the function keyword and can accept parameters and return values. Functions can be recursive, calling themselves within their own code. A callback is a function passed as an argument to another function.
    • Objects Objects store collections of data in key-value pairs. Objects can contain properties (data) and methods (functions). The this keyword refers to the object in which it is used. A constructor function is used to create objects.
    • Prototypes Every JavaScript object has a prototype property. Prototypes allow objects to inherit properties and methods.
    • Classes Introduced in ES6, classes are templates for creating objects. They contain a constructor method for initializing object properties and can have other methods.
    • DOM (Document Object Model) The DOM represents HTML documents, allowing JavaScript to manipulate webpage content and structure. Methods like getElementById, getElementsByName, getElementsByTagName, querySelector, and querySelectorAll are used to select HTML elements. JavaScript can modify element attributes, styles, and classes using DOM manipulation techniques.
    • Events Events are actions that occur in a web browser, like clicks or mouse movements. Event listeners are used to execute code in response to specific events. Common events include mousemove, mousedown, mouseup, mouseover, mouseout, keydown, keyup, and scroll.

    JavaScript DOM Manipulation Essentials

    DOM (Document Object Model) is an API for manipulating HTML documents. The DOM represents an HTML document as a tree of nodes, where each HTML tag, attribute, or text is a node.

    Selecting Elements To access and manipulate elements within an HTML document, JavaScript provides several DOM methods:

    • getElementById(id): Retrieves the element with the specified id attribute.
    • getElementsByName(name): Returns a collection of elements with the given name attribute.
    • getElementsByTagName(tagname): Returns a collection of elements with the specified tag name.
    • getElementsByClassName(classname): Returns a collection of elements with the given class name.
    • querySelector(selector): Returns the first element that matches the specified CSS selector.
    • querySelectorAll(selector): Returns a collection of all elements that match the specified CSS selector.

    Traversing Elements Once an element is selected, you can navigate the DOM tree to access its related nodes:

    • parentNode: Gets the parent node of the specified node.
    • firstChild: Gets the first child node of the specified element.
    • lastChild: Gets the last child node of the specified element.
    • childNodes: Gets all child nodes of the specified element.
    • firstElementChild: Gets the first element child of the specified element.
    • lastElementChild: Gets the last element child of the specified element.
    • nextElementSibling: Gets the next sibling element of the specified element.
    • previousElementSibling: Gets the previous sibling element of the specified element.

    Modifying Elements JavaScript provides several ways to modify HTML elements:

    • createElement(tagname): Creates a new HTML element with the specified tag name.
    • appendChild(node): Adds a node to the end of the list of child nodes for a specified parent node.
    • textContent: Gets or sets the text content of a node and its descendants.
    • innerHTML: Gets or sets the HTML code within an element.
    • after(node or string): Inserts one or more nodes or strings after the element.
    • append(node or string): Appends new nodes or strings to the end of the children of an element.
    • prepend(node): Adds a new node as the first child of an element.
    • insertAdjacentHTML(position, text): Inserts HTML code at a specified position relative to the element.
    • replaceChild(newchild, oldchild): Replaces a child element with a new one.
    • cloneNode(deep): Clones an element, optionally including its descendants (deep is a boolean value).
    • removeChild(child): Removes a child element from a node.
    • insertBefore(newnode, existingnode): Inserts a new node before an existing node as a child of a parent node.

    Attribute Manipulation HTML attributes can be accessed and modified using the following methods:

    • attributes: Returns a collection of all attributes of an element.
    • getAttribute(name): Gets the value of the attribute with the specified name.
    • setAttribute(name, value): Sets the value of an attribute.
    • hasAttribute(name): Returns a boolean value indicating whether the element has the specified attribute.
    • removeAttribute(name): Removes the attribute with the specified name.

    Style Manipulation The style of an element can be manipulated using the style property:

    • element.style.property: Gets or sets the value of an inline style property.

    Class Manipulation CSS classes of an element can be manipulated using the following properties:

    • className: Gets or sets the class name of an element as a string.
    • classList: Returns a collection of CSS classes of an element, providing methods to add, remove, toggle, and check classes.
    • add(classname): Adds a CSS class to the element.
    • remove(classname): Removes a CSS class from the element.
    • replace(oldclass, newclass): Replaces an existing class with a new one.
    • contains(classname): Checks if the element contains a specific class.
    • toggle(classname): Adds the class if it doesn’t exist or removes it if it does.

    Events Events are actions that occur in a web browser. Event listeners are used to execute code in response to specific events. There are three ways to assign event handlers:

    • Using HTML attributes.
    • Assigning event handler names in JavaScript.
    • Using the addEventListener method.

    The addEventListener method accepts three arguments: the event type, the function to be executed when the event fires, and an optional boolean value indicating whether to use capture. The removeEventListener method removes an event listener that was added using addEventListener.

    JavaScript Events and Event Handlers

    Events are actions that occur in a web browser, like clicks or mouse movements. An event handler, also known as an event listener, is a piece of code that will be executed when the event occurs.

    There are three ways to assign event handlers:

    1. Using HTML attributes: For each event, there is an event handler, and their names typically begin with on. For example, the event handler for a click event is onclick. The JavaScript code can be added within the quotes of the HTML attribute. The event handler attribute can also call a function. When the event occurs, the web browser passes an event object to the event handler. Inside the event handler, the this keyword refers to the target element on which the event occurs.
    2. Assigning event handler names in JavaScript: The event handler can be added to the HTML element in the JavaScript code. For example, element.onclick = function(){}. In this method also, the this keyword refers to the target element. To remove the event handler, assign null to the event handler.
    3. Using the addEventListener method: The addEventListener method registers an event handler, and the removeEventListener method removes an event handler that was added using addEventListener. The addEventListener accepts three arguments: the event type, the function to be executed when the event fires, and an optional boolean value indicating whether to use capture.

    Some useful JavaScript events:

    • mousemove: Fires repeatedly when you move the mouse cursor around the element.
    • mousedown: Fires when you press the mouse button on the element.
    • mouseup: Fires when you release the mouse button on the element.
    • mouseover: Occurs when the mouse cursor moves from outside to inside the boundaries of the element.
    • mouseout: Occurs when the mouse cursor is over an element and then moves to another element.
    • keydown: Fires when you press a key on the keyboard and fires repeatedly while you are holding down the key.
    • keyup: Fires when you release a key on the keyboard.
    • keypress: Occurs when you press a character keyboard like ABC and fires repeatedly while you hold down the key on the keyboard.
    • scroll: Occurs when you scroll a document or an element.

    When an event occurs, the event flows from the most specific element to the least specific element; this is event bubbling. When the event starts at the least specific element and flows towards the most specific element, this event model is known as event capturing.

    JavaScript Prototypes: Inheritance, Properties, and Methods

    In JavaScript, every function and object has its own property called prototype. A prototype itself is also an object, creating a prototype chain.

    Key aspects of JavaScript prototypes include:

    • Prototype Inheritance You can use the prototype to add properties and methods to a Constructor function, and objects inherit the properties and methods from a prototype.
    • Adding Properties To add a new property to a constructor function, use function name.prototype.property name = value.
    • Adding Methods To add a method, use function name.prototype.method name = function(){}.
    • Accessing Properties and Methods Objects created with the constructor function can access the properties and methods defined in the prototype.
    • Changing Prototype Values If a prototype value is changed, all new objects will have the changed property value, while previously created objects will have the previous value.

    For example, consider a constructor function Person:

    function Person(first, last) {

    this.firstName = first;

    this.lastName = last;

    }

    To add a new property called gender to the Person constructor function, use the prototype:

    Person.prototype.gender = “male”;

    To add a method called getFullName, use the prototype as well:

    Person.prototype.getFullName = function() {

    return this.firstName + ” ” + this.lastName;

    }

    Now, create two objects using the Person constructor function:

    const person1 = new Person(“Elon”, “Musk”);

    const person2 = new Person(“Bill”, “Gates”);

    The objects person1 and person2 can access the gender property and getFullName method:

    console.log(person1.gender); // Output: male

    console.log(person2.getFullName()); // Output: Bill Gates

    JavaScript and the DOM: Manipulating HTML Elements

    The sources provide information on manipulating HTML elements using JavaScript, primarily through the DOM (Document Object Model).

    Selecting HTML Elements To begin manipulating HTML elements, they must first be selected. Several DOM methods are available for this purpose:

    • getElementById(id): Selects an element by its id attribute.
    • getElementsByName(name): Retrieves all elements with a specific name attribute.
    • getElementsByTagName(tagname): Selects all elements with a given tag name.
    • getElementsByClassName(classname): Selects all elements with a specified class name.
    • querySelector(selector): Selects the first element that matches a CSS selector.
    • querySelectorAll(selector): Selects all elements that match a CSS selector.

    Traversing HTML Elements After selecting an element, it’s possible to navigate the DOM tree to reach related elements:

    • parentNode: Accesses the parent node of an element.
    • firstChild: Accesses the first child node of an element.
    • lastChild: Accesses the last child node of an element.
    • childNodes: Provides a collection of all child nodes of an element.
    • firstElementChild: Accesses the first element child of an element.
    • lastElementChild: Accesses the last element child of an element.
    • nextElementSibling: Accesses the next sibling element of an element.
    • previousElementSibling: Accesses the previous sibling element of an element.

    Modifying HTML Elements JavaScript offers various methods for modifying HTML elements:

    • createElement(tagname): Creates a new HTML element with the specified tag name.
    • appendChild(node): Adds a node as the last child of a parent node.
    • textContent: Sets or retrieves the text content of an element, ignoring HTML tags.
    • innerHTML: Sets or retrieves the HTML content within an element, interpreting HTML tags.
    • after(node or string): Inserts a node or string after a specified element.
    • append(node or string): Appends a node or string to the end of an element’s children.
    • prepend(node): Adds a node as the first child of an element.
    • insertAdjacentHTML(position, text): Inserts HTML at a specified position relative to an element.
    • replaceChild(newchild, oldchild): Replaces one child element of a node with another.
    • cloneNode(deep): Clones an HTML element. The deep argument specifies whether to clone all descendant nodes as well.
    • removeChild(child): Removes a child element from a node.
    • insertBefore(newnode, existingnode): Inserts a new node before an existing node.

    Working with HTML Attributes Attributes of HTML elements can be accessed and changed with these methods:

    • attributes: Returns a collection of all attributes of an element.
    • getAttribute(name): Retrieves the value of the attribute with the specified name.
    • setAttribute(name, value): Sets the value of an attribute.
    • hasAttribute(name): Checks if an element has a specific attribute.
    • removeAttribute(name): Removes an attribute from an element.

    Manipulating Element Style The style property is used to manipulate the inline styles of an HTML element:

    • element.style.property: Retrieves or sets the value of a CSS property.
    • element.style.cssText: Sets multiple CSS properties at once. Using += with cssText allows appending new styles without overriding existing ones.
    • getComputedStyle(element): Returns an object containing the values of all CSS properties of an element, including those from external stylesheets.

    Manipulating Classes CSS classes can be manipulated for styling purposes:

    • className: Gets or sets the class name of an element. Assigning a new value overwrites existing classes, but concatenation can be used to add classes without removing existing ones.
    • classList: Provides methods for adding, removing, and toggling CSS classes.
    • add(classname): Adds a class to an element.
    • remove(classname): Removes a class from an element.
    • replace(oldclass, newclass): Replaces one class with another.
    • contains(classname): Checks if an element has a specific class.
    • toggle(classname): Adds or removes a class, depending on its presence.
    JavaScript Full Course For Beginners With JavaScript Projects Tutorial And Notes 2024

    The Original Text

    hi guys welcome back to another video of greatest tack if you think JavaScript is difficult to learn and tired of watching multiple tutorials of JavaScript and still not feeling confident well you have come to the right video by the way this is not just a simple video but it is an ultimate course to start your journey into the exciting world of JavaScript in this JavaScript course we will start from the absolute Basics and I will guide you through the fundamentals of JavaScript that will help you to build a solid foundation in this course we will cover the introduction of JavaScript then we will see the basics of JavaScript where we will learn about the variables scope operators keyword reserved keywords and expression then we will see the data types and after that we will see the difference between primitive and reference values then we will move to operate s where we will learn about the arithmetic operator assignment operator logical operator comparison and then we will move to control flow statements where we will learn about if if else statements for while and do while loop and break and continue statement after that we will see the functions functions are important Concepts in JavaScript so in the function we will learn about the function parameters arguments return keyword in the function then we will see the anonymous function recursive function and default parameters after that we will learn about the objects and prototype where we will learn about the key values and method in the object then we will see the Constructor function prototype object D structuring and object literal syntax extensions after completing the object we will learn about the classes classes are also very important in JavaScript so in the classes we will learn about about the class getter and Setter methods then we’ll see the class Expressions inheritance static methods and private methods after completing the classes we will move to the Dom which is document object model so in this Dom we will learn about the notes then we will learn about get elements and query selected methods then we will see the create and clone element then we will learn add nodes to document then we will see get elements details using the Dom then we will learn about the modifying element using Dom then we will see get and modify the element class using the Dom then we will learn about the events available in this Dom each concept is clearly made to be beginner friendly with clear explanation and practical examples along with this I will also provide you the complete notes of this course in the video description but here is the best part it’s not just Theory at at the end of this tutorial we will make some real world projects like online Notes app Quiz app form validation image slider digital clock and e-commerce product page don’t worry you will not need any prior coding experience before starting this course by the end of this course you will be writing JavaScript code with confidence so are you ready to master JavaScript hit that subscribe button and help me to get the 5,000 likes on this course now let’s dive into the world of JavaScript together welcome to JavaScript introduction tutorial in this tutorial we will learn what is Javascript why you should learn JavaScript what is the use of JavaScript and how to write your first JavaScript program so what is Javascript JavaScript is a scripting language that is used to create interactive and dynamic websites interactive website means user can perform some action on website for example button click submit a form write comments and live chat Dynamic website means the website that changes its content or layout like sliding effect e-commerce website and quiz website why you should learn JavaScript JavaScript is the most popular programming language in the world it is used in almost all popular websites like Google Facebook Twitter Amazon Netflix and many others great thing about JavaScript is that you will find tons of Frameworks and libraries to reduce your time to create websites and mobile apps some of the popular Frameworks are react angular and vuejs if you learn JavaScript it opens a lot of job opportunities in the software development Industries what what is the use of JavaScript uses of JavaScript is not only limited to front-end web development it is also used in backend web development mobile app development desktop app development game development and API creation using JavaScript you can easily create websites like Amazon and Netflix mobile apps like Instagram and WhatsApp games like Tic Tac to and snake game you can also create mini JavaScript projects like to-do list app Quiz app Notes app weather app calculator or image gallery I already have 30 mini JavaScript projects on my YouTube channel that you can check out from the link given in the video description and these projects are more than enough to learn and practice JavaScript how to write your first JavaScript program to start with JavaScript you need to have a web browser and a code editor I’m using Google Chrome web browser and visual studio code editor I already have a tutorial how to download and install Visual Studio code editor you can find the video link in the description so let me open my code editor here I have one HTML file with basic HTML structure in this HTML page you can see we have the head open tag and head closing tag and this is the body open p and closing tag so the first option is to add the JavaScript code within the head tag so before closing of this head tag we can add our JavaScript code so let me add one a script tag a script open and closing tag like this and within this script we can add our JavaScript code so let me add one line of JavaScript here alert welcome to greatest stack this JavaScript code will give instruction to browser to alert this message welcome to greatest stack so let’s open this web page you can see this message welcome to greatest tack click okay so this was the first option to add the JavaScript code in the SML file now the second option is to write the JavaScript code within the body tag let me remove this script from here we have to add the code within this body tag so I will add it here a script open and closing tag within this we have the JavaScript code to alert one message welcome to greatest tag now let’s open the web page again and again you can see this message welcome to greatest tag so this JavaScript code written within the body tag is also working now let me remove it from here also there is another option to add the JavaScript code in the HTML file that is external Javascript so to add the external Javascript we will use a script SRC and the new file name so here let’s create a new file name and write the file name script.js you can write your own file name but the file name extension should bejs I’m writing a script.js you can write main.js index.js anything so this is the new file script.js and next we have to add this file here a script SRC and the file path a script.js so we have added the file path here now let me open the folder in this intro folder you can see there was one HTML file and now we have one more file the script.js and we have connected the script.js with the HTML file with thist script tag and now we can add our JavaScript code within this external file so here we will add alert welcome to greatest tag after adding this let’s come back to the website and now you can see this alert message welcome to greatest tag so this JavaScript code is also working now let me come back to the HTML file and we can move this a script tag in the head also like this and it will also work you can see this alert is working let me place it here within this body tag there are multiple options to display the output of JavaScript on the web page or browser so here I have added alert welcome to greatest T so we can see the message in the alert box there’s another option we can add document dot write welcome to greatest stack we can write like this document. write so it will write this message in the web page let’s see our web page you can see this message welcome to greatest tack it is written on the website now we have one more option here if I write console do log this will give the output in the browser console tab so let me show you come to this browser right click and select inspect it will open this developer tool and here you have to click on Console let me Zoom it click on Console we can change the theme by clicking on this setting icon appearance and do so this is the console tab here you can see this message welcome to greatest tag because here I have added console.log welcome to greatest tack if I change the message JavaScript tutorial come back to the website you can see welcome to greatest Tech here because I have added document. write and here you can see JavaScript tutorial because I have added console.log so it will add this message in the console Tab and in this console also we can add our JavaScript code we can write and execute the JavaScript code within this console tab also so let me show you one example if I write 4 + 5 and we got the result 9 so it is executing the JavaScript code here let me add one more thing if I write console dolog hello and hit enter you can see we have added console.log Hello and it is printed here hello now if you want to display the output on the browser alert box we can write like this alert hello hit enter you can see this alert box with the message hello now you can display the output on the website also let me add document dot WR and here we will add the message hello click enter you can see the Hello message on the website so this is how you can display the JavaScript output on your website or browser console and now you know how to write your JavaScript code so this was all about JavaScript introduction and writing your first JavaScript program what is variable in JavaScript variables are used to a store data it is like a container where we use to store things at home to declare a variable in JavaScript we use the V let and const keyword we can write where X here where is the keyword to declare a variable and X is the identifier or name of the variable we can also declare variable like let X or const X the V keyword is the oldest and the most common way to declare variables theet keyword is a newer keyword that was introduced in es6 we will learn about es6 later in the advanced JavaScript the const keyword is used to declare constants which are variables that cannot be changed once you have declared a variable you can assign a value to it using using equal sign for example where xal to 30 the following code declares a variable called X and assign it the value 30 variables can be used to store any type of data including number a string objects and arrays for example if I write where x equal to double quote or single quote any message hello world so here we are storing the string data type in the X variable variables name must begin with alphabet dollar sign or underscore if I write 2x it is not a valid name for the variable if I write anything in the alphabet it is valid and we can also declare it with the dollar sign we can start like this dollar X it is valid and we can also use underscore here like this underscore X let me remove it so you can see it is valid format to write a variable name you can start with dollar and you can start with any alphabet in upper case or lower case it is valid but if you start from the number it is not a valid name for the variable if you add the valid character then later you can add number it is valid JavaScript is case sensitive so if you write where first name equal to greatest stack and if you write first name with the lowercase end so these two variables name are different it is not same because here we have the different case so JavaScript is case sensitive that’s why it is two different variables name now let’s understand about the let keyword let keyword in JavaScript is used to declare a block scoped variable this means that the variable is only visible within the Block in which it is dict cleared for example if I write let x equal to 10 and if x greater than 5 yes it is greater than 5 because the x value is 10 in this block we will add let y = to 20 and here if I try to display the value of y we will add console do log y so you can see this y value in the console tab here you can see 20 correct we have added this code within this curly bres so it’s a block and if I try to access this y outside of this block we will copy this and paste it here here outside of this block and now if I try to run it you can see one error reference error why is not defined so if you try to access the Y value outside of this if statement you will get a reference error this is because variable Y is not defined outside of this block now let’s understand about the const keyword so the const keyword in JavaScript is used to declare a con Conant variable this means that the variable cannot be reassigned to a new value for example if I write const a equal to 4 so we are assigning a value for in the a variable now if I print this console do log a we will get four in the console tab now in the next line if I try to write AAL to 5 we are trying to reassign a new value a equal to 5 and run this you can see we got an error assignment to constant variable so we cannot assign a new value in constant variable now let’s learn about the scope in Java JavaScript scope in JavaScript refers to the visibility of variables and functions within a program in JavaScript there are three type of a scope Global scope function scope and the third one is block scope so let’s learn about the global scope the global scope is the outermost scope in the JavaScript program variables and functions declared in the global scope are visible from anywhere in the program let’s understand it with one example if I write where x equal to hello greatest stack and here we create one function called example and in this one if if I try to print this message if I write console do log X and now we have to call this function example now you can see this message in the console tab hello greatest stack over here in this example we have declared a variable X outside of any function or block which makes it a global variable Global variables are accessible from anywhere in the script including inside a function and we have declared this outside of the function so we can access it within the function and outside of the function also if I simply add this here and it will also print this you can see Hello greatest stack two times the first one is printed using this console.log written inside the function and the second message is printed using this console.log x so this was the global scope now let’s understand what is the function scope so the function scope is created when a function is declared variables and functions declared in a functions scope are only ual within that function so let’s understand this function scope with one example here we will add function example here we will create one variable where FS function scope equal to hello greatest stch and if I try to display the output we will add console. log fs and now just call this function so now you can see this message hello greatest TCH because we are accessing this variable inside this function now if I try to access this FS outside of this function let’s copy this and paste it here outside of this function and try to run it we got an error FS is not defined why because we have defined this FS variable inside this function so it is a function scope variable and now we are trying to access this FS outside of this function it is not accessible so the variables and functions declared in a functions scope are only visible within that function now let’s understand the block scope so the block scope in JavaScript refers to the visibility of variables and functions within a block of code a block of code is a group of statement that are enclosed in a curly braces variables and functions declared in a block scope are only visible within that block let’s understand block scope with one example let’s create one function and in this one we will create one block true and here we are creating one block with this curly bres So within this if we will add one variable so let’s add the variable name block variable BV equal to create a stack and here if we try to display this console.log BV and just call this example now you can see this message greatest stack in the console tab here because we are accessing this variable inside this block now if I try to access this variable outside of this block it is declared inside this block and if I try to access here this block is closing here so let’s add this line here at line number n and now if I try to run you can see we got an error in line number nine BV is not defined because we are accessing this variable outside of this block let’s try to access this variable outside of this function only let’s remove it from here and add it here at the end and now you can see the error message at line number 12 BV is not defined because we are trying to access this variable outside of this block so the variable and functions declared in a block scope are only visible within that block so this was all about the variables and the scope in JavaScript data types in JavaScript data types is an important Concept in any programming language to perform any task with the data it is important to know its type data types in JavaScript are divided into two categories primitive data type and reference data type there are seven primitive data types in JavaScript which are a string number buo null undefined big int and symbol so let’s learn about the string data type in JavaScript a string is a sequence of zero or more characters a string starts and end with either a single quote or a double quote JavaScript strings are for storing and manipulating text for example if I write let first name equal to double code elone so here we are adding one name in double quote it is a string and the variable name is first name let me duplicate it here we will add last name and if I write the text in single quote musk it is also a string it is written in double quote and this is written in the single quote now let’s see another data type which is number number represents integer and floating Point numbers for example if I write let num equal to 100 in this statement we have declared one variable called num and initialized its value with the integer 100 let me change the value if I write 96.5 it is also a number type here we have stored the floating number if we write 96.0 then JavaScript will convert it into an integer number to use less memory so it will be saved only 96 let me show you that if I write console.log num so you can see 96 is printed here it is not printing 96.0 it is printing 96 only because the JavaScript is converting this floating number into an integer and if I type 96.5 it will be saved as 96.5 and if we change 96. it will be only 96 now let me tell take another example if I write let x equal to 10 so here I have stored one number in the X variable let me write console.log X here we will get 10 in this console tab we got 10 now if I add a single quote in this 10 now it will become string because we are adding single quote in this text now if I print this one you can see still it is displaying 10 but if you will check the data type it will be a string the value is 10 but the data type is a string to check the data type we have one operator called type of in front of this variable name if I write type of X you can see we got the data type string because this 10 is written inside the single quote if I change it and make double quote still it will be string you can see string here now if I remove this quote and if we only write 10 then it will be a number you can see it is number when we will add double quote or single quote it will be stored as a string now the next data type is Boolean the Boolean data type has two values true and false let’s understand it with one example if I write let learning equal to true and and let completed equal to false here we have stored Boolean data in the learning variable and completed variable now to check this one we will add console.log learning you can see true so it is display the value stored in this learning now to check the type of the data stored in this learning we will again use the type of operator type of learning so it is displaying the data type Boolean now let’s check the data type of this another variable which is completed just copy this one add it here here it will display the data type Boolean for the another variable called completed now if you want to display the value stored in this completed here I’m adding console.log completed and it is displaying false here which is the value stored in the completed variable and it is the type of the value which is Boolean so we have stored the true or false value directly but we can store the result of any expression for for example if I write let X = to 20 greater than 10 so the result of this is true 20 is greater than 10 it is true so now if you want to check the value stored in the X we will add console.log X and now you can see it is displaying true here we are writing 20 greater than 10 but the X has stored the result of this expression which is true now if I change if I write 20 less than 10 which is false so you can see the result in the console tab it is displaying false so we have stored the false in the X variable now let me show you the type of the data here we will add type of X and now it is displaying Boolean so this x has a store the Boolean data type next primitive data type is undefined if a variable is declared but the value is not assigned then the value of that variable will be undefined and the data type is also undefined let me show you this with one example let H we have declared a variable age but we have not assigned any value now we will check the value stored in this age let’s add console.log age here you can see the value is undefined now if you want to check the type of the data here we will add console.log type of age now you can see the value is also undefined and the type is also undefined if we add any value like this a is 30 now you can see the value is 30 and the type is number and when we remove it we have not assigned any value so the value is undefined and type is undefined so this was undefined data type next pleas primitive data type is null in the JavaScript null is a special data type that represents empty or unknown value let’s understand it with one example here if I write let number equal to null and now we will try to print the value here we will add console log number so you can see the result it is displaying null now we will try to display the type of the data so here in the next line we will add console.log type of number you can see the value is null but the type is object the type should be null but it says the type is object it is a known bug in JavaScript JavaScript defines that null is equal to undefined to check this one we will write console.log null comparison operator then undefined so we are comparing null with the undefined and here you can see we got the result true it means in JavaScript null is equal to undefined there are two other primitive data types which are symbol and B that we will study in our upcoming videos now let’s learn about the reference data type so the first reference data type is object in JavaScript an object is a collection of properties where each property is is defined as a key value pair so let me create one object here if I write let person equal to curlys that’s it so the following code defines an empty object this is the person object which is empty now let me display the data stored in this person object for that we will add console.log person that’s it now you can see we got the empty curly bles now to check the type of the data we will copy this one and here we will add type of person so you can see the result the data is empty in this curly Braes and the data type is object now let’s add some properties in this person object here we will add first [Applause] name last name and age let’s add 35 so you can see in the console tab the data type is object and this is the data stored in the person object first name Elon last name musk age 35 an object can store different data type in this person object the first name and the last name are string and this age is number so this person object can store different type of data it can also store another object our next reference data type is array arays are a type of object that stores a collection of values for example if I write let number we have have added five different number separated by comma in the square bracket so the following code creates an array of numbers now let’s print the value of this number we will add console.log number so in the console tab you can see this aray is printed 1 2 3 4 and 5 the same thing is printed here now if you want to check check the type so let’s add this line again and in this one we will add type of operator type of number now you can see in the console tab we got the type object so the array is also an object data type our next data types is function functions are a type of object that can be used to execute code for example here we will create one function to create a function we use the function keyword and the name of the function so let’s add the function name MSG that is for the message and in this one just add one console.log and here we will add one string hello greatest tag so we have declared one function with the function name MSG now if you want to check the type of the data here we will add console.log type of MSG that is function name and if I check this in the console tab you can see it is displaying function it says the type of data is function but it is also an object data type Javas script is a dynamically typed language so we can store different data type in the same variable for example if I write let X here we are not assigning any value so the data type will be undefined so let’s check this one type of X it is displaying undefined let’s check the value also if I write console.log X console.log type of X so it will display the value stored in the X and it will display the data type now you can see in the console tab it is displaying the value undefined and data type undefined now in the same variable we can store different data type here we have already declared the variable so we will just add X we are not declaring we are just assigning the value x equal to let’s say one string greatest tag so here we are adding one string in the X variable let’s try to to print this you can see in the console tab it is printing undefined and undefined from here now we have changed the data it is greatest tag which is string so you can see the value and the data type is a string now again we can change the type of the data we will simply store another data let’s add x equal to 100 so here we have stored the number let’s try to print this now you can see in the console tab we have the value 100 and we have the type number so earlier it was undefined then it is a string then it is number now let’s add one more example if I write X true and in the console tab you can see it is true and the data type is Boolean so the JavaScript is dynamically typed language so we can store different type of data in the same variable and in this one you can see the example also it is undefined it is string it is number it is Boolean so this was all about the data types in JavaScript operators in JavaScript operators in JavaScript are symbols that are used to perform operations on operants operant are the values and variables so let’s understand it with one example here if I write 10 + 20 here plus is an operator and 10 and 20 are operant here is the list of different operators that we will learn in this tutorial arithmetic operators assignment operator comparison operators logical operators and string operators now let’s learn arithmetic operators arithmetic operators are used to perform mathematical operations on operants there are multiple arithmetic operators so first one is addition here we will add let sum equal to 5 + 3 and console.log sum so in the console tab you can see we got the sum which is 8 5 + 3al 8 this is the addition operator now let’s learn the second one which is substraction here we will add substraction it will be x 5 – 3 three it will be X now you can see two in the console tab because 5 – 3 is 2 so this is the substraction now the next one is multiplication if I write five multiply 3 now you can see the result 15 now the next one is division operator for division views forward slash let’s add 15 ided 3 now you can see the result 5 15 / 3al to 5 now the next one is reminder or modulus here we will add modulus and to get the modulus we use percent symbol and and if I write 17 perc 4 now we will get the modulus 1 you can see when you divide 17 by 4 you will get the reminder 1 which is modulus now the next arithmetic operator is exponentiation when you write 2 to ^ 4 2 to the^ 5 that is exponential so to calculate the exponential here we will add X two double star and four so it means we will add 2 into 2 into 2 four times like this so what will be the result you can see in the console tab 16 so if you write dou star it will be exponentiation operator so these are arithmetic operators now let’s learn about the assignment operator assignment operators are used to assign values to variables we use equal sign to assign operator for example let X = to 5 here we are using equal sign which is the assignment operator and we write the value on the right side of the operator so this was the simple assignment M operator now we have other assignment operator also like addition assignment so let’s see that we have the x value 5 now we will add X Plus equal to 3 so if you simply add x = 3 it will replace the value in this x variable and the X will become three but here we are adding plus it means this three will be added in the existing value of this x so the current value of x is 5 and 5 + 3 will be 8 let’s check the output console. log X and in the console tab you can see the value8 so this was the addition assignment similarly we have the substraction assignment here we will add minus equal to 3 now we will get the output two you can see the output 2 now we have the multiplication here we will add multiply 3 so this three will be multiplied with the current value which is 5 5 into 3 and now you can see the output 15 next one is division assignment you can see this value here after that we have the modulus assignment you can see see the modulus 2 now the next one is exponentiation assignment dou star equal to 3 it means we are writing 5 to the^ 3 and it will be 5 * 5 * 5 so the result is 125 now let’s learn about increment and decrement operators the increment and decrement operators are used to increase or decrease the value of a variable by one suppose the variable value is five it will be incremented by 1 and it will become six or it will be decremented by one it will become four the increment operator is Plus+ and the decrement operator is minus minus increment and decrement operators can be used in two ways which is prefix and postfix so let’s learn prefix increment and decrement operator let me add one example here let a equal to 10 in the next line I’ll add console. log Plus+ a we are adding increment operator before the variable name which is a now you can see the output 11 because the value of a has been incremented by one now let me add one more line console.log a so in this line the value of a is incremented by 1 then it is printed 11 and in this line the current value of a is printed the current value is 11 in this example operator is placed before the variable and the value of the variable is increased before it is used now let’s see prefix decrement operator so for decrement we will add minus minus and in the console tab you can see the output 9 and 9 so it is decreasing the value of a by 1 then it is printed here and in the next line we are printing the current value of a which is 9 now let’s learn about the postfix increment and decrement operator in the postfix we add the operator after the variable so if I remove this and add Plus+ after a now you can see the output first it is printing 10 and after that 11 here we are adding A++ but still it is printing 10 because a is printed first and after that it is increasing the the a value by one now the next time I will print the a value it will display the updated value here it is displaying 11 in this example operator is placed after the variable and the value of the variable is used before it is incremented the same thing will happen with the decrement post fix operator if I run this one you can see current value of a is 10 and first it is printing the value 10 after that it is decreasing the value by one and if I print the new value of a it is N9 so this was the increment and decrement operator now let’s learn about comparison operator comparison operators compare two values and give back a Boolean value either true or false comparison operators are useful in decision- making and loop programming in JavaScript let’s see some example if I write like this it will be the less than operator it is greater than this will be less than or equal to this is greater or equal to this will be equal check it will check the equality of two values it will be inequality or not equal and it will give the flip value of the equal checks we will understand it with the example also and this one is the strict equality check it checks the data type also I will also explain it with example and it is the strict inequality or flipped value of the strict equality check now let’s understand these comparison operators with example here if I add let a = to 10 b equal to 20 and here we are adding less than operator you can see console. log a less than V so it will give the result true in this one it is checking a greater than b which is false a is 10 B is 20 so a greater than b is false so it will give the result false now it is a less equal to B so it will be true and this will be false a greater or equal to B it is false because a value is 10 now here we are checking a equal equal B it means a value is equal to B is not equal it is 10 and 20 so it will be false in this not equal we will get the flipped result of this equality check so the equality check was false so this will be true and this is the strict equality check and this is the strict unequality check so let’s print this one you can see the first one is true a less than b true a greater than b false a less than equal to B this true a greater equal to B it is false A = to B 10 = to 20 which is false a not equal to B so it will be true now in the next line we are adding a strict equal so A and B is 10 and 20 it is not equal so we will get false and it will be the opposite it result true now let’s understand it with other example if I remove this and here if I write like this 10 and it will be 10 so a is 10 as a string and B is 10 as a number now let me add one more thing here console.log a equal equal B now you can see the first one is true why a is 10 B is 10 then it is true now in the next line we are adding a triple equal to V it is giving false why first it will check the data type so in this one the data type is a string and the data type is number in the B variable then it is different so it is not equal so that’s why it is giving false and the last one is giving true because it will give the flipped value of this false our next topic is logical operators logical operators perform logical operations like and or not for logical and we use this symbol for logical or we use this symbol and for logical not we use this exclamation symbol so let’s learn about the logical and logical and evaluate op and return true only if all are true in this line you can see the first condition is true and the second is true and here we are adding logical and operator so both are true that’s why the result will be true now in this one the first one is true second one is false so both conditions are not true that’s why it is false here also one of the condition is false it is false here both conditions are false that’s why it is false only when both conditions are true then only the result will be true now let’s understand logical and operator with one example here I have added let X = to 5 and y equal to 10 and I’m adding X greater than 0 so this condition is true X is obviously greater than z y is also greater than zero then the first condition is true second is also true then the result will be true you can see the first result is true now in the second condition you can see X greater than 0 which is true y less than 0 which is false 10 less than 0 is false right then one of the condition is false that’s why the result is false now in The Third One X less than Z which is false then the result will be false and in the last one 5 less than 0 is false and Y isal to 10 which is 10 less than 0 which is false so both conditions are false that’s why the logic result is false so this was The Logical end now let’s learn about the logical or logical or returns true if one of the multiple operant is true if any one oper is true then it will return true so here you can see the first one is true true and second one is true so the output will be true first one is true second is false still the output is true first one is false second is true then the output is true in the last one first condition is false and second condition is also false then the result will be false so if all operant are false then the output will be false and if any one of the operant is true the result will be true now let’s understand this logical or with one example here we have the a value 5 b value 10 and a greater than Z true B greater than Z true so both conditions are true then result will be true now here the first one is true this is false then still it is true it is false it is true then still it is true now in the last one for first one is false second one is false so both operant are false so the result is false so this is the logical or operator now let’s learn about The Logical not logical not converts operator to Boolean and return flipped value let’s understand it with one example if I write let yes is equal to True let no equal to false we are adding two variable yes and no and yes is true no is false and if I try to print not yes not operator and yes then it will give the flipped result earlier it was true now it will display false you can see the first one is false here in the second one we are adding not no so the no value is false so the not no will be true you can see the not no is true so this is The Logical not operator our next topic is Javascript string operators in JavaScript you can also use plus operator to concatenate or join two or more strings let me explain this with one example if I write console.log and in this one in this one we will add two string let me add hello Plus World and let’s see the console tab you can see hello world is printed here if you need one space we will add it here now you can see it is printed with one space hello world we we can join the string using the addition assignment operator Also let’s see another example if I write let a equal to JavaScript and in the next line I will add a addition assignment operator plus equal to and here we will add another text so let’s add a space tutorial in the current value of a the current value is Javascript and in this JavaScript it will add this tutorial let’s print it in the console you can see this text JavaScript tutorial is printed in this console tab so this is how you can join or concatenate strings in JavaScript using the plus operator so this was the string operator in JavaScript there’s one more operator in JavaScript which is bitwise operator bitwise operators are rarely used in everyday programming that’s why we will skip this one our next topic is operator precedence operator precedence in JavaScript determines the order in which operators are passed concerning each other let me take one example let result equal to 2 + 3 * by 4 so what will be the output here if you add 2 + 3 it will be 5 and 5 * by 4 it will be 20 so this will be output or it will will be 4 * by 3 12 + 2 = 14 so which is the correct answer so the correct value is 14 let me show this result in console tab now in the console tab you can see the output 14 why because the 3 * by 4 is performing first and after that it is adding two so why multiplication is performed before addition it is because of the operator’s precedence value in this table you can see the Precedence of multiplication and precedence of addition so the higher precedence is performed first that’s why it is multiplying three and four after that it is adding two and the result is 14 so this was operator precedence now let’s learn about Operator associativity Operator associativity in JavaScript defines the order in which operators of the same precedence are evaluated there are two type of operator associativity left to right right to left in this table you can see the operator name and their associativity now let’s learn about the left to right associativity in left to right associativity operators are evaluated from left to right let’s take one example if I add let result equal to 4 – 2 – 1 in this example only substraction operator is used and its associativity is left to right as you can see in this table the expression 4 – 2 – 4 is evaluated from left to right first 4 minus 2 will be evaluated and it will give the result 2 then 2 – 1 will be evaluated and it will give the result one so let’s check the result in the console tab you can see the result one so this was left to right associativity now let’s learn about the right to left associativity in right to left associativity operators are evaluated from right to left for example let result equal to two exponentiation 3 exponentiation 2 in this example only exponentiation operator is used and its associativity is from right to left as you can see in this table first three exponentiation 2 is calculated resulting in N then 2 exponentiation 9 is evaluated and giving the result 500 12 so let’s see the result in the console tab here if I write log result you can see the result 512 so this was all about the JavaScript operators control flow statements in JavaScript control flow statements are used to control the flow of execution in JavaScript program they are used to make decisions execute loops and handle errors there are three type of control flow statements in JavaScript which is conditional statements loops and try catch statements so now let’s learn about conditional statements conditional statements are used to execute different code based on different condition the most common conditional statements in JavaScript are are if a statement else a statement and else if a statement if a statement in JavaScript is used to execute a block of code if a condition is true so let’s understand it with one example here we will add if and in this parenthesis we will add one condition condition will be true or false so we will add true in this block let’s add one line of code execute so in the console tab you can see this message execute in this example the condition is true that’s why it is executing this code and it is printing execute in this console tab now if I change it here we will add false and now in the console tab you can see nothing is printed why because if the condition is false then any code written within this block will be skipped it will not execute now let’s understand it with another example here we will add age greater than 18 and let’s add let age equal to 20 and and it will print one message you are an adult so here we have the age value 20 and the condition is age greater than 18 so you can see 20 is greater than 18 that’s why this block of code will be executed and we will see this message here now if we change the value of this age let’s add 16 now in the console tab you can see it is blank nothing is printed why because this condition is false 16 greater than 18 is false that’s why this code will not be executed let me comment this and we will take another example and here let’s understand with another example we will add let country equal to India and let age equal to 20 if age greater equal to 18 and operator country equal to India so this is the if statement where we are adding two conditions using the logical and operator here we are adding logical and that’s why if the first condition is true and second condition is true then only this complete line output will be true so you can see the age is 20 which is greater than 18 and country is India and here it is comparing with India so this condition is also true and this is also true then overall result is true so we can print any message console.log you can get a driver’s license now you can see it is printed here in this console tab you can get your driver license now if I change the age value to 17 now nothing is printed in this console tab it is empty so you can add this type of logical or logical and operator to get the true or false value and then if the value is true then only this code will be executed now let’s learn about the if Elsa statement if Elsa statement in JavaScript is a conditional statement that is used to execute a block of code if a condition is true and another block of code if the condition is false so let’s understand it with one example here we will add the same example here you can see if the condition is true then only this code will be executed now we have to add another statement that will be executed when the condition is false so here just add else in this else condition I will print another message console.log you a minor now you can see in in the console tab we got an message you are a minor why because the age is 18 so the if condition is false here we are adding 16 greater than 18 which is false so if it is false then else condition will be executed and if I change the value 19 you can see the message you are an adult the if condition is getting executed next conditional statement is else if so in this example we have one if condition and one else condition now we need another condition also so here we will add else if and in this one let’s add one condition check here we will add age greater equal to 16 it will be greater equal to 18 and in this else if let’s print one message console.log you are a teenager so what will happen in this program first it will check if it is 19 this if condition will be executed now if this condition is false suppose the value is 7 1 now it will jump to the next statement the first one is false it will come to the next statement which is else if and in this one it will check whether the condition is true or false if the condition is true then only this code will be executed else it will go to the another statement so here let’s check age is 17 and 17 is greater than 16 correct so that’s why this condition is true then this code will be ex uted now let’s check this one and you can see in the console tab we got the message you are a teenager it is printing from this console.log which is in the else if statement like this you can have multiple else if a statement suppose this is also false let’s add 15 age is 15 so this condition is false this condition is also false so it will execute the else condition condition else condition is ur minor you can see in the console tab the message Ur minor now you know the if statement else if statement and else statement now we will learn about this switch in JavaScript the switch statement in JavaScript is a conditional statement that is used to execute a block of code based on the value of an expression let’s understand the switch with one example here if we write let value is equal to 42 and then we will add the switch statement so this is the syntax to write this switcher statement in this one we will add type of value so it will get the type of this value variable and the type is number for now now in this case we will execute different message we can create multiple cases so in the first case let’s add number so if the type is number then we will print console.log number we can add multiple case so let’s duplicate it and here we will add string console.log string let’s add another one it will be Boolean console.log bullion in the default we will add console.log other now in this switch statement you can see the output is number why because we are adding value is equal to 42 which is is the number type and here it will check the case if it is number then it will print number now if we change the type if I add hello so the type of this variable is a string so it will check this case it is not correct then it will check this case so the type is a string correct that’s why it is printing this message now if I change it let’s add true so the type is Boolean so this case will be executed and it will print Boolean now if I add anything else let’s add one array now you can see other is printed here because this case is also false this is also false this is also false so it will print the default one so in this default we have added message other that’s why it is printing other in this console tab now let’s take another example of this switch case here we will add day name and the day name let’s add two suppose the day start with Sunday Monday Tuesday and the number is 1 2 3 for Sunday it is 1 Monday it is two so here we are adding let day name is equal to two now let’s add the switch statement went went in this one we have to pass the day name so let’s add switch day name as a key and here we will add different values so first value will be one and here day name is equal to Sunday now we will add second case case 2 so the day name will be Monday let’s add case three so we have added seven different Case Case 1 2 3 4 5 6 7 and name of the day wednessday Thursday Friday Saturday suppose we have entered Any number greater than 7 then we will display another message so here in this default we will add day name is equal to invalid day number now to print this we will add console.log let’s add the message the day is plus day name this is the string and this is the variable now in the console tab you can see the day is Monday why because we have added day name two now let’s change it here we will add five and we will check the console tab you can see the day is Thursday let’s add seven so it will check this case one then it will check two then it will check three so it is seven so it will come here case and the value is seven then day name will be Saturday and it will be printed using this console the day is Saturday so this is the switch case statement in the JavaScript now we will learn Turner operator it also works like if else a statement let me write the example of if else a stat M so here we have added let age equal to 20 if a greater than or equal to 18 so if this condition is true this code will be executed and if this condition is false then else statement will be executed now the same thing we can execute using the Turner operator for Turner operator we use this question mark now let’s see the Syntax for the Turner operator first we will add condition then question mark and after this question mark we will add the code that will be executed if the condition is true so here we will add value if true now we will add column and here we will add the code that will be executed if the condition is false value if false this is the syntax to use the Turner operator now let’s understand with example so here we will add the same thing let age is equal to 20 and now we will add the condition like this age greater equal to 18 question mark if it is greater then what we will print we will print Ur an adult this will be the message and if it is false this condition is false then we will print you are a minor we can directly write console.log and this message so it will be printed in the console tab so this will become so long that’s why here I’m adding let MSG is equal to this either this message or this message will be stored in this MSG now we will add console.log MSG let’s see the output in the console tab you are an adult now if I change the value it will be 16 now check this you are a minor so this is how the Turner operator is working same as the F statement so this was all about the conditional statements Loops in JavaScript in programming Loops are used to repeat a block of code for example if you want to display a message 100 times then you can use a loop first we will learn about the for Loop syntax of the for Loop is this one you have to add for then in this parenthesis we are adding the initial value of I after that we are checking the condition if this condition is true then only this code will be executed and after execution of this code written in this curly reses it will increase the value of I by 1 now let’s understand the for loop with one example suppose I want to print one message 10 times for that here let’s add console.log and in the message I will add greatest stag so I want to print this greatest stack 10 times let’s start it with one initial value of I is 1 and I want to print this for 10 times so here we will add less than equal to 10 this is simple now if I run this code you can see Greatest Tag is printed 10 times you can see 10 here we are printing the same message 10 time that’s why the browser will collapse it and display only one line and here it will display 10 it is printed 10 times now let’s take the another example of for loop I want to print number from 1 to 10 for that this for condition will be same here we will just add I so first what will happen the I value will be one and it will be printed using this console. log I after that it will increase the value so the I value will be 2 and it is less than 10 right then it will print two again it will increase the value that will be I3 and IAL to 3 is less than 10 so 3 will be printed so like this it will be printed up to 10 now run this code and you can see 1 2 3 up to 10 is printed in this console tab we can use Loops for printing the data of an array let’s take another example let me comment it and here I will add let coding equal to one array and in this array I will add JavaScript python C++ now I want to print the JavaScript Python and CPP using for Loop to get the element we use the index so index I start with zero JavaScript is at zero index python have index one CPP have index two so let’s write the for Loop here we will add for let’s add let I is equal to 0 because index starts with zero now I will be less than the length of array so this is the array dot length so AR length is three maximum index value is two that’s why I’m adding I less than coding do length that is 3 I Less Than 3 after that we will add i++ and in this C adds we will add the code that has to be executed every time so here we will add console.log coding and I first it will execute coding zero then coding one and coding two so coding zero will display JavaScript coding 1 will display Python and coding two will display CPP so you can see the output in this console tab JavaScript Python and CPP so you can use the loop on ADD also we can create another loop inside a loop let’s see another example here we already have this code this is the first Loop and let me make it small I’ll add one to five and it will print the number from 1 to 5 and after that we will add another loop inside this Loop here we will add for and here we will add another variable name let’s add let Jal to 1 so initial value is 1 next we will run this Loop for three times so here we will add J less than equal to 3 then increase the value of J and in this we will print another message let’s add console.log and here we will add one message inner loop plus J now you can see the output in the console tab first it will execute this code and after that it will come to this for Loop now this for Loop will be executed for three times and in three times it will print inner loop one inner loop two inner loop three here we will add a space so you can see inner loop 1 2 3 now again it will increase the value of I so I will be two and this will be printed console. log I so 2 will be printed in the console tab you can see two is printed here and after this again this for Loop will be executed and it will again print from the 1 to 3 you can see 1 2 three now again the I value will be increased by one it will be three and three is printed here and again it will execute this inner loop now you can see the message inner loop 1 2 3 again the outer loop will be executed console. log I I will be 4 so this is how you can use another loop inside a loop now we will learn while loop syntax of while loop let’s add V and in this parenthesis we will add condition then in this curly Braes we will add the code that has to be repeated so this is the syntax of while loop which is very simple so in this one we have to add one condition and this code will be executed until the condition is true when the condition is false it will stop the loop now let’s understand the Y loop with one example we will print number from 0 to 10 so here let’s add console.log let’s add I and we have to declare this I so here we will add let I equal to 0 because we have to print the number from 0 to 10 now in this condition we will add I less than equal to 10 so first it will check the I value I value is zero so if the value is less than 10 then it will print the value of I now it will print the same value again and again so we have to increase the value so in the next line we will add i++ so first it will print the value then it will increase the value now you can see the output 0 1 2 up to 10 so this while loop is repeating this code until the I value is less than or equal to 10 suppose the I value is 10 so 10 less than equal to 10 is true it will print this value that is printed here now it will increase the value by 1 so I will become 11 now it will again go to this condition and 11 is less than equal to 10 that is false once it is false then it will stop this Loop next we will learn do while loop do while loop is also very simple so this is the Syntax for do while loop first it will execute the code written in this do statement and after that it will check the condition if the condition is true then it will again execute this code and when the condition is false it will stop this Loop now let’s understand it with one example let’s write one code to print a number from 1 to five using do while loop so here we will add let IAL to 1 and it will print using console tab console.log I and here it will check the condition we will add I less than equal to 5 here we have to increase the value of I so let’s add i++ now you can see the output in the console tab 1 2 3 4 5 so first the I value is 1 then it will come to this statement and it will print the value of I 1 then it will increase the value by 1 so it will become two so 2 is less than equal to 5 that is true so again it will print the value so it will be printed here then it will become three and 3 is less than equal to 5 that is also true again three will be printed here like this it will print one to five series now let’s change the value of I to 10 if I add IAL to 10 you can see the output 10 is printed here why it is printed because do Loop will execute the code first time then only it will check the condition so first it will print the value of I I isal to 10 so console. log I will be printed here 10 then it will increase the value 11 then the value of I will be checked here I less than equal to 5 which is false so it will not execute the code again but the first time it will be printed so this was for Loop while loop and do while loop apart from this there are some other Loops also like for off for in that we will study in advanced JavaScript now we will learn about break and continue statement in JavaScript the break statement is used to terminate the loop immediately let’s understand this with one example let’s take one example of for Loop for printing 1 to five number this for Loop is printing number from 1 to 5 you can see in the console tab now if I add one if condition here before printing this number here we will add if I comparison operator three when the I value is three then we will add break so you can see what will happen when it will get the break statement it will terminate the loop it will stop the loop you can see in the output only one and two is printed first time the I value will be printed then second time the I value will be printed that will be two then third time I will be three and here it will be checked if I is equal to 3 it will get this break statement and after that it will terminate the loop only IAL to 1 and two is printed here so this is how we use the break to terminate the loop or exit the loop now we will learn about the continue the continue statement is used to skip the current iteration of the loop and the control flow of the program goes to the next iteration let’s see the example here if I write continue then what will happen first the I value will be one so it will not be executed then I will be two it will not be executed then I value will be three once the I value is three it will get this continuous statement when it will get the continuous statement it will skip the remaining code of this for Loop it will directly come to the next iteration it will increase the value of I by 1 so I will be for so the four will be printed now you can see the output 1 2 4 5 3 is not printed because when the I value is three it will skip this part and the I will become four then again four will be printed so this is how break and continue statement works so this was all about the for Loop while loop do while loop break and continue in this tutorial we will learn about function in JavaScript a function is a block of code that performs the specific task functions in JavaScript are reusable block of code that can be called from anywhere in your program here is the syntax to declare a function a function can be defined using the function keyword followed by the function name the body of a function is written within this curly process now let’s create a function to print a text we will use the function keyword and the function name is GRE to print any text we will add console.log and message in the double code now we need to call this function to execute the code written in this function for calling this function we will use the function name and parenthesis so simply we will add great and this parenthesis so this estate will evoke the function or call this function after that you can see the output in the console tab hello Greatest Tag is printed here so this is the function declaration using the function keyword and the function name this is the body of function where we will add the code that will be executed within the function and this code is for calling this function or evoke the function now we will learn about parameters and arguments parameters are the variable that are declared in the function definition while the arguments are the value that are passed to the function when it is called let’s see one example of function with parameters we will create one function with the function keyword and the function name is gr and in this one we will add two parameters first name comma last name so this first name and last name are variable that are declared while declaring this function this is known as parameter now we will add the code in the body of this function here we will add console.log and we will add the text hello plus there will be first name then we will add plus and one space within double quote then again we will add plus and last name so it will print hello first name and last name in the console tab so right now we have declared the function with two parameters now we have to call this function while calling this function we have to pass two values that will be arguments so to call this function we will add the function name GRE and with this function name we have to add two values so let’s add first value Elon comma musk so we are passing two values when calling this gr function now you can see the output in the console tab here it is printing hello Elon Musk let’s add a space here now it looks good hello Elon Musk is printed in this console tab we can pass any data type as argument so let’s add another data type I will add 200 that will be number here also we will add 100 now see the output you can see it is printing hello to 200 and 100 so we can pass any data type as argument while calling the function we can pass less or more arguments while calling a function if we pass less arguments then the rest of the parameters will be undefined if you pass more arguments then additional arguments will be ignored let’s see one example if I just pass GRE alone and comment this first call here you can see the output it is saying hello Elon and undefined because we are passing only one argument and here we have two parameters first name and last name so this alone will be stored in this first name so it will print hello and the first name is Elon and in the second parameter which is last name we are not passing any argument so it will be un defined that’s why it is printing hello Elon undefined the last name is undefined so we can pass less argument now let’s see another example if you pass more arguments here if I add Alon comma musk comma Mr now see the output here it is printing hello Elon Musk so the first argument will be stored in the first parameter which is first name second argument will be stored in the second parameter which is last name and this third parameter will be ignored because we have only two parameters here so it will only print this hello and the first name Elon and last name musk the third argument will be ignored now let’s learn about default parameters default parameters in JavaScript are parameters that have a default value this means that if the argument is not passed to the function the default value will be used let’s see one example of default parameters here we will create one function write the function name sum and in this sum function we will add two parameters which is X and Y now in this body of function we will add console.log and it will log the X + Y it will add the X and Y value and it will display in the console tab now to call this function we will add function name and parenthesis but here you can see we have two parameters X and Y so when calling this function we have to pass two arguments also so let’s add two values 10A 15 15 so this 10 will be stored in x 15 will be stored in y and this console. log will display 10 + 15 that will be 25 you can see in the console tab it is printing 25 10 + 15 now you can see if I remove 15 from here and we are just passing 10 10 will be stored in X and Y will be undefined and here we are printing x + y so let’s see what will be output here it is printing n n why it is because here we are adding 10 plus undefined x + y will be 10 plus undefined that’s why it is printing NN that means not a number we cannot add the undefined n number so it is printing an N here we are passing only one parameter and you want this function to work for that we can add Y is equal to 0 suppose we have added y value zero then you can see the output in the console tab it is printing 10 let’s see if I add 50 we are passing 50 in X and Y default value is zero so x + y that means 50 + 0 that will be 50 you can see the output 50 is printed so 0 is the default value of this y parameter and here if we pass two numbers 50 + 30 then it will use 30 in this y you can see the output 50 + 30 80 is printed here because we are passing two arguments 50 50 will be stored in x 30 will be stored in y so this was the default parameters in Javas script now we will learn about function return the return statement can be used to return the value when the function is called the return statement donates that the function has ended any code after return is not executed let’s see one example if I create one function and function name is ADD and in this one we will add two parameters A and B now we can add return A+ B so this function will return the addition of A and B now to call this function we will add the function name add and in this one we have to add two values as argument so we will add 10 and 20 so this will call this function and this function will return the addition of 10 + 20 so we can store this result so here let’s add one variable with the let keyword let result equal to add function so the return of this add function will be assigned in this result variable now we can print this result we will add console do log the sum is result now you can see the output in the console tab it is displaying the sum is 30 if we add 10 and 40 you can see the output in console tab the sum is 50 so this return statement will return the value if we add any code after this return a statement like a multip by B this code will not be executed return statement denotes that the function has ended any code after this return statement will not be executed in JavaScript a function can return another function Also let’s see one example here if we create one function with the function name fn1 so this is the first function here I’m adding one parameter X in this function one we will create another function let’s create function fn2 and this will accept one parameter y now in this second function we will add return X multiply y so so the function two will return the multiplication of X and Y next after this function two we will add return FN 2 so when we will call this function one it will execute this function two also and then it will return this function two so function one is returning another function that is function two to call this function we will add fn1 parenthesis and we will pass one argument so let’s add three so here we are calling function one and passing one argument let’s store its value in one variable we will add let result is equal to function one and try to print this result console DOT log result so you can see the output in the console tab here it is displaying one function so you can see when I am calling this function one it is returning the function two and that function two is stored in this result now the function two is stored in this result so we can simply call this result like this result for the second function also we need one argument so we will add two and let’s print this one we will add console.log and print this result two you can see the output it is displaying six because in function one I passing three that will be X and function two I’m passing two that will be y and x * by y will be 3 * 2 is = to 6 let’s understand this example again again here we have the function one this function one has return a statement and this return a statement is actually returning the function fn2 which is declared here so the function is returning another function now we can store the return value in any variable so here we have called and stored the return of the function one in result with this console log we can see what is stored in this result so in this result function two is a stored so to call this function two we will add result and we will pass one argument so this was another example of return a statement in JavaScript function so this was all about function in this video we will learn callbacks in JavaScript a callback is a function passed as an argument to another function a callback function can run after another function has finished let’s understand the callbacks with one example I’m creating one function and the function name is display and this display function will display the message in the console tab so here we will add console.log and let’s add result and this result is parameter so here we have declared One display function that will only display the result in the console tab we are not performing any calculation in this function now we will create another function let’s add the function keyword and the function name is add this add function will have three parameter let’s add num one then num two and the third one will be one function let’s add my call back in this add function we will add let sum is equal to num one plus num two so this sum variable will store the value of num 1 + num 2 next we will add this call back and and in this call back we will add Su now we will call this add function so just add the function name which is ADD and parenthesis and this function has three parameters so we will pass three argument so first one will be one number that we want to add again we will add another number 1020 and in the next parameter we will pass one function so we have already created this display function so we will pass this display function in this add function when you pass a function as an argument remember do not use the parenthesis we will simply add the function name there is no parenthesis required so let’s understand this code here we have declared one function that will just display one message in the console then we have another function that have three parameters s it will add the two number and store the value in some variable now to print this sum in console we need to call this display function so when calling this add function we are passing the two numbers 10 and 20 that will be added and we are passing this display function as argument and this function will be here in my callback this display function also accept one argument so here I adding my callback and the value which is sum so this my callback will call this display function so let’s see the output in the console tab you can see it is printing 30 we are calling add function and in this add function we have not added console.log the console.log is added in the another function called display and we are passing this display function as argument in the add function function let’s change the value if I write 20 + 30 and now again check the output you can see it is displaying 50 that is 20 + 30 so when we are passing one function as an argument to another function that is known as callback function in JavaScript now let’s learn about Anonymous functions Anonymous function in JavaScript are functions that are not declared with a name here is the Syntax for anonymous function just write the function keyword and parenthesis and add your code within the curly Braes we can add parameters also in Anonymous function so this is the syntax to create Anonymous function we are not adding any function name we are just adding function keyword and parenthesis and curly Braes now let’s see one example of anonymous function here we will create one function with the function keyword this function will have two parameters X and Y now this function will return the value of x + y here I’m creating one function without any name so it will not be stored on our memory so to access this function we can store this function in any variable so let’s add let keyword to create one variable and the variable name is sum sum is equal to function here we have declared one function and assigned this function in a variable called sum this is known as function expression to call this function we can use the sum variable here we will add sum and this function accept two argument so we will add the two two value in this parenthesis 10 and 15 now to print this value in the console tab we will add console.log and write this sum and two parameters now you can see the output in the console tab it is printing 25 let’s change the value here we will add 10 and 30 now again you can see the output 40 so let’s understand this example again here I’m creating one function without any name and assigning this function in variable called sum to access this function or call this function we can use this sum variable and this function accept two argument so with this sum we are passing two argument 10 and 30 this 10 will be stored in X and 30 will be stored in y so it will return the X x + y value that will be 40 that will be printed in our console tab now let’s see another example of anonymous functions here we will create one function with the function keyword and write the parenthesis and within the curly braces we will add console.log and one message welcome to greatest de here we have declared one function without any name but how to execute the code written in this function as you know to call any function we write the function name and parenthesis so this will call or execute the function we will add the same thing with this Anonymous function also we will trap this Anonymous function in a parenthesis like this we have wrapped it in this bracket and now we will add this parenthesis that will execute this function now you can see in the console tab it is printing welcome to greatest stack the function is executed immediately when the script runs and it logs the message welcome to greatest T to the console now let’s see another example of anonymous function here we will add set timeout function and time set time out is built-in method in JavaScript that accept one function and time in milliseconds so here let’s add 2,000 milliseconds and here we will create one function so here we can add one Anonymous function let’s add function keyword then parenthesis and curly Braes and in this curly Braes we can add the code that will be be executed within this function so let’s add console.log hello creest stag here I’m adding an anonymous function that display the message hello greatest tack in console and here I’m adding 2,000 milliseconds so it will execute this function after 2,000 milliseconds that is 2 seconds let’s see the output in the console tab you can see it is blank but after 2 second it display the message hello greater stack now increase the time if I add 5,000 milliseconds that will be 5 seconds and run the code again you can see the console is blank and after 5 Seconds it will print hello greatest stag you can see it is printing hello great stack in the console we can write like this so it will be clear now you can see we have declared one function without any name so this is another example of anonymous functions now we will learn about recursive functions in JavaScript a recursive function in JavaScript is a function that calls itself let’s create one function and the function name is my function and within this function we can write the code and after that we will call the same function here we will add my function and parenthesis so in this one you can see we have declared one function with the name my function and within this function we are calling the same function my function parenthesis now to evoke this function we will add it here outside of this function here my function is recursive function because it is calling itself inside the function a de cursive function must have a condition to stop calling itself otherwise the function will be calling itself infinitely to prevent infinite recursion we can use if else statement or any condition statement so here if I add if if condition and within this condition we will call this recursive function and else stop calling recursion so this is just one example how we can create one recursive function and call the recursive function and how to prevent the recursive function for infinite recursion we can add the if Els condition or any other conditional statements of JavaScript now let’s see one example I want to print numbers in descending order so here we will create one function and let’s add the function name countdown so this countown function will accept one number so here we will add num to call this function we will add the function name countdown and we will pass any number let’s add 10 so this will call this countdown function and pass the number 10 in this num now to print this number we will add console.log num so this will will be printed in the console tab now I want to print 10 9 8 7 like this so we have to decrease the number so after printing the number in console we will decrease its value by one so simply we can add num minus minus so it will decrease the value by 1 if the number is 10 it will become 9 so after decreasing the number again we have to print it so to print the number again we can call this function again let’s add countdown num so this countdown num will again a start from here and it will again print this but this countdown will be running infinitely so to prevent the infinite recursion here we will add if num is greater or equal to Z so when the number is greater or equal to Z then only it will call the function again now you can see the output it is printing 10 987 65 4 3 2 1 0 it is printing the number from 10 to 0 Let’s understand this code again here we have declared one function and in this function it is printing the number and it will decrease the number by one and after that it will check if the number is greater or equal to zero then it will call this function again so this countdown function is calling itself this is known as recursive function so this is all about recursive function callback function and Anonymous functions in JavaScript object in JavaScript JavaScript object is a non-primitive data type that allows you to store multiple collections of data let’s see the syntax to declared an object we will use const keyword then object name so this is an object in this we can add the data in key value paired we will add key 1 value one we will add the comma to separate the data we will add another key key2 and value two we can use the let keyword also to declare one object but it is good practice to use the const keyword let’s see one example if I write the object name person and in this person object we will add the name of the person so first we will add first name and in the first name we will add Elon add one comma then we will add the last name the value is musk and we will add one more information age so here we have created one object with the object name person in this object we have three properties now let’s check the type of this person we will add console.log type of person now you can see in the console tab it is printing object so the type of the person is an object now if we want to print the complete object we will add console.log person in this console you can see it is printing the object that we have created it is printing age 35 first name and last name any object can store two things which is properties and methods in this person object data is stored in key value pairs first name is the key Elon is the value age is key 35 is value these key value pairs are called properties key is always stored as a string here if I write this name in double quote still it will be correct you can see there is no error in the output you can see it is displaying simply first name so by default it will store it as a string in the value we can add any data type we can add a string number arrays Boolean function and we can store an object also when we declare a function as has a value in key value pair then it is known as methods now let’s learn how to access the properties of an object we can access the values of a property by using its key name so the first way of accessing the property is using dot notation we can write object name dot key so it will give the value stored in the key value pair of the object let’s access the value stored in this person object here we have the console.log person and if you want to access the name stored in the first name so we will add person. first name and we will check the console you can see it is printing Elon so we can access the property using dot notation let’s add the age here if you want to access the age object name and key so it is displaying the value in the console you can see it is printing 35 the second way of accessing the properties of an object is using bracket notation so in this example here we will remove this Dot and add a square bracket and we will add this text in double quote as a string now you can see the console tab it is printing 35 so we we can access the property by using braet notation and in this braet we have to add the key name with double quote or single quote let’s add the first name so you can see the first name in the console Alon keys in object are stored as a string so we can add this key in double code like this and we can add a space Also here we are adding first space name like this now if you want to access the value stored in the first name we will add console.log and object name and if you use dot here DOT first name it will give an error we cannot access this property by using do notation in this case we have to use the bracket notation only and in this bracket notation will add the string in double code or single code then you can see it will display the name it is displaying the name alone in the console tab so the bracket notation is also useful to access the properties of an object now let’s see how to update the properties of an object so we have this object person and in this one if I want to update the first name so the first name is Elon and I want to change it so we can add the object name that is person and write the key that will be first name and we can assign a new value or a new data so here we will add Mr Elon Mr Elon so this line will update the first name in the object called person now you can see the output it is displaying Mr Elon because here we are printing person. first name here we have declared one object with the person and here the first name is Elon and in this line we are updating the first name with the new name which is Mr Elon and Mr Elon is printed using this console.log next we will learn how to add a new properties in the object so here we have the object with three properties and now I want to add one more property so for that we will add the object name so the object name is person then we will add the key so key is company so this line will add a new property in the person object now if you want to display the object just add console.log and object name now you can see the console tab it is displaying the object with four properties age company first name last name so we have added one new property company and it is displaying in this object next we will learn how to delete one property from the object so let’s use the same example and here we will add the delete keyword delete then write the object name and key so let’s delete the age that’s it we are adding delete keyword then object name and key now if you want to check let’s see the console tab here you can see it is displaying only three property which is company first name and last name age property is missing because we have deleted age property from this object this is how you can access the properties of an object you can update the property you can delete the property and you can add a new property as I have already discussed in value we can store any type of data so we can store one object also that is nested object so let’s take the same example in this one we will add one more property here we will add address and this address will contain another object that’s it we will add the data in key value pair in this example you can see we have an object called person and in this object we have three properties then we have added one more properties and this property is having one another object that is known as nested object and in this object also we have added the data in key value pairs you can see Street city state country and zip code now to access the data stored in the nested object we can use the same dot notation let’s add console.log write the first object name person and in this object we have the address we will add address and from the address we can access CT now you can see the console tab it is printing Austin now if you want to access ZIP code right person address ZIP code now you can see it is displaying zip code in this console so so this is how you can access the properties of the nested object now we will learn how to check if a property exist in an object to check if a property exist in an object you can use the in operator we can write property name in object name here we have the person object so let’s see one example to check if the property exist in this person we will add age in person it returns true if the property exist in the object so let’s print this in console tab we will add console.log we have to add this age in quotes now you can see in the console it is printing true because age exist in this person now if you want to check first name is exist or not so here we will add first name in person so it will display true because we have the first name in the person object now if you will add country country in person now you can see it is displaying false because in this person object we don’t have any property with the key name country now if you want to display all properties and values of an object without knowing the property name then you can use foreign Loop foreign Loop allows you to access each property and value of an object without knowing the specific name of the property for example we will add for and in this one we will add one variable so let’s declare one variable with the let keyw word and we’ll add the variable name prop that is properties and prop in object name person now we can print this prop so let’s add console.log prop in the console you can see it is printing first name last name and age because in this person object we have three keys first name last name and age so using the for in Loop you can access all properties of an object now if you want to access the values stored in this key we can use the bracket notation as we have already discussed to access the value we use the object name like person and bracket notation and in this one we will add the key so let’s add H so it will display the value so here we will add the same thing let’s add person Square bracket and prop so you can see the output in console tab it is displaying the values only the values are Elon Musk and 35 now if you want to display both key and value so let’s add prop plus and here we will add colum now you can see the output in the console tab it is displaying both key and values stored in this person first name Elon last name musk is 35 so using the for in Loop you can access all the properties of an object there are multiple ways to create an object in JavaScript this was the example to create an object with object literal let’s see another example where we will create an object with the new keyword for that we will add const [Music] person new object so this is the another way to create an object if you want to add some data in this object we can add the object name and key and assign one value so it will add this data in this person object let’s duplicate it and we will add another data last name age now if you want to display this person object just add console.log person you can see in the console tab it is displaying one object with the data Age first name last name so you can see we have created one object with the new keyword and then we have added these data in this person object we can add these data while creating an object Also let’s see I will remove these things remove it from here and in this object just add curly Braes and within this curly Braes write the data in key value pair and here it will be comma now it will create the same thing you can see the output it is same still it is displaying the object with three properties first name last name and AG so this was all about JavaScript object and their properties in this video we will learn about JavaScript object methods JavaScript method is an object property that contains a function definition let’s create one object with the const keyword here we will add the object name person and in this object we will add two properties first name and last name let me create one more property here and I will add the property name GD you can call it property name or key in this gr property we will declare one function to declare a function we use function keyword then name of the function so let me write the function name g and in this function we will print one message using the console log hello world so in this one you can see we have the third property with the function definition this is called as object methods so this is the method of the person object now to call this method we will add the object name that is person and then write the method name GRE and write the parenthesis also now you can see the console tab it will display the output hello world so in the person object we have created one property with the function definition that is known as method and we are calling this method using the object name do method method name parenthesis here we have declared one regular function we can add the anonymous function Also let’s remove this name and we can write like this here we have used function expression to define a function and assign it to the GD property of the person object and still it will display the same message in the console tab hello world we can declare a function outside of the object and assign it to an object as a method here is one example let me remove this function from here and here we have one object with two properties now we will declare one function function name is grd and console.log hello world next we will assign this function inside this person object so here we will add person dot any key name so we will add the key name greeting is equal to greet let me add T it will be correct so in this line I’m assigning this greet in this person greeting now to display the output we will add the person dot greeting parenthesis now you can see the output it is displaying hello world so let’s understand this example again here we have created one object and the object name is person where we have only two properties now we have declared one function and assigning this greet function in this person object the property name or key name is greeting we are calling this method using person. greeting parenthesis now if you want to display this person object simply we will add console.log person now in the console tab you can see it will display the object and in this object you can see we have the first name then this greeting property which is the method in this greeting we have the function definition so this is how you can assign one function inside an object as a method es6 provides us one more way to declare a method for an object let me remove it and in this object we can simply add gr and curly Braes and write the code so this is one more way to declare one function in inside the object as a method we can access this method using the person dot GRE now you can see it will display the message hello world in the console tab now we will learn about JavaScript this keyword to access the other properties of an object within a method of the same object we can use this ke key word let’s see the same example one object with the name person and we have two properties first name and last name now to access the first name we use to write object name do the key name or first name so this is how you can access the property of an object but when we need to access the first name within the method so in this one let’s create one method here we will add one method G one Anonymous function and message console.log hello now in this method if I want to display the first name so here we will add plus this DOT first name so when we need to access the property of an object outside of the object we use the object name and key so we are adding person do first name but here we are accessing the first name inside this method and this method is in this person object so this keyword refers to the same object which is person so we don’t need to write the object name we can simply write this keyword do first name so this will print hello and the first name now to call this method we will add the object name Person dot gr let’s see the output in the console tab it is printing hello Elon let me add a space here now you can see it is printing hello Elon in the console tab so we can use this keyword to access the properties of the same object within the method so when we use this keyword within a method it refers to the same object now let’s define a method that Returns the full name of the person object by containing its first name and last name so remove it and let’s remove this method also and here we will add another method get full name one function and in this function we will add return this function will return the first name and last name to access the property we will add this DOT first name then we will add space so let’s add double quote then Plus this do last name it will access the last name so in this method you can see it is returning this do first name so it will return this value Elon and here this do last name it will return this value musk now to call this method we will add person dot get full name this method is returning some value so we can print it using console.log let’s add console.log person. get full name now you can see the output in the console tab it is printing Elon Musk so it is returning the full name by containing first name and last name let’s understand this example again here we have an object with the name Person where we have two properties first name and last name and one method this method Returns the first name and last name of the person now we are calling this method so it will display the full name which is Elon Musk we can use this keyword outside of the method also but it will refer to the other object let’s remove all these things and here simply add console.log this so here you can see the output it is display Ling window object so if we use this keyword alone or inside a function then it will refer to the global object that is window object or when we use this keyword in the event then it will refer to the element that receive the event this keyword is not a variable so we cannot change the value of this so this is all about JavaScript method and this keyword in this tutorial you will learn about JavaScript Constructor function and and how to use the new keyword to create an object in JavaScript Constructor function is used to create objects let me create an object we will add the const keyword then object name person and in this object we will add properties so the first property is first name and the second property last name this example create a person object with two properties first name and last name but this syntax is used when you have to create single object in programming you often need to create many similar objects like person to do that you can use a Constructor function let me create one Constructor function for that we will add function keyword and then the name of the function person then parenthesis and in this curly braces we will add properties so let’s add this DOT first name and value Elon again this Dot last name and value Constructor function is similar as a regular function but it is good practice to capitalize the first letter of the Constructor function so you can see here I have added capital P in this person a Constructor function should be called only with the new operator we can use the new operator to create an object from a Constructor function till now we have not created any object we have just created one Constructor function to create a new object we use the new operator so let’s see how to create an object using this Constructor function let’s add the con keyword then we can write any name of the object so let’s add the person one this is the object name here let’s add new operator and write the function name person so this line will create one new object that is person one using the Constructor function we can create multiple objects so let’s add one more line here we will add person two so here we are creating another object with the name Person two with this person Constructor function now if you want to see what is stored in the person one console.log person one and see the output in the console tab so you can see the person one is one object with the two properties first name and last name now let’s see the second object also so we will add console.log person two so we are printing both person one and person two in the console so let’s see the output here you can see both output is same when a new object is created using the Constructor function this keyword will refer to the newly created object so in this example here we are creating one new object person one with the new operator and this Constructor function so this keyword will refer to the newly created object which is person one and this first name and last name will be added in this person one as a property so in this example person one and person two object have same property value but we can create multiple object of the same type with different property value also using Constructor function parameters so as you know the parameters in the function here we will add parameters in this Constructor function also so in this function let’s add first last in this Constructor function we are adding two parameters first and last and this first will be stored in this first name this last will be stored in this last name now when calling this Constructor function we have to pass two arguments here we are creating object by calling this Constructor function so to call this Constructor function we have to pass two arguments so let’s pass two value Alon musk for creating this person to object we will pass another argument let’s add another name billgates so in this example here we have one Constructor function with two parameters so to call this Constructor function we have to pass two arguments so this Elon will be here in this first and this first will be stored as a value in this first name property this mask will go here in the last and this last will be stored as the value in this last name property so when we are creating person one it will create one object with the property first name and last name and the value is Elon Musk and when we’ll create the person two object it will also create the object but the value will be different that will be buil gets now let’s see the person one and person two object in the console tab so you can see the output here in this console so in the first object you can see first name Elon last name musk and in the second object we have first name will last name gets so using the Constructor function we can create multiple object of the same type now let’s see how to add properties and methods in an objects so first let’s add one property in person one object so removing this console and here I will add person one to add a new property in this person one just add Dot and the property name age and write the value let’s add 52 now we can print this in the console let’s add console.log person one you can see in the console tab here we have three properties in this person one object which is first name last name and age and the age value is 52 that we have added here person 1. AG is equal to 52 now if I simply want to print the age here we will add console.log person one do age so you can see the console tab it is only printing the value stored in this age property that is 52 now if I try to access the age from the person two let’s see what will happen here I’m adding person to. age and see the output in the console tab it is displaying undefined because we have added this age property only in the person one object we have not added in the person two object that’s why person 2.as will display undefined now let’s see how to add one method in the person two so let’s scroll and here we will add person two dot method name we will add gr and declare one function as we have already studied method is a function decaration inside the object property so here in this person two object we are adding one method with the name gr and declaring one function and let’s say this function will log one message hello great stack we have to write it in codes so we have added one method in the person two object now let’s access this method here we will add person 2 dot GD from person 2 we are calling this GRE method now let’s see the output in the console tab it is printing hello great stack in the console tab so this is the example to add a method in the object now let me remove this and you can see in this Constructor function I have added added only two properties now let’s see how to add one method in the Constructor function so here let’s add one comma and here we will add this dot name of the method get full name and here we will declare one function so this method will return some value so return this DOT first name then we will return the last name Also let’s add one space plus and this do last name so here I’m adding get full name and this method will return first name plus last name that will return the full name name so we have just created The Constructor function now we have to create object also so let me add the same example again I will add person one and person two so we have created person one and person two object using the new operator and Constructor function now let’s see how to access the get full name method so to access the full name just we will add person 1 dot get full name the method name now this method is returning some value so we can print it using log console.log person 1.g full name now you can see the output in the console tab it is printing Elon Musk now let’s access the person two full name and you can see the output billgates the problem with this Constructor function is is that when we create new object using this Constructor function the same method will be created in all the objects created using this Constructor function which is not memory efficient to resolve this we can use the Prototype of the object so that all objects created from this person Constructor function will share this same method so this is all about JavaScript Constructor function in this tutorial you will learn about JavaScript object prototype in JavaScript every function and object has its own property called prototype let’s create one object const person and this person will have name Elon so this is one simple object with only one property that is name but this person object has one more property called prototype let’s see this person object in the console we will add console.log person and you can see in the console tab here it is displaying one object name Elon right but if I expand it you can see the property name Elon but here we have one more property called prototype and the Prototype is also an object a prototype itself is also another object so the Prototype has its own prototype let’s expand this prototype again and expand any of this you can see here again we have the Prototype let’s expand another one here also we have prototype so the Prototype has its own prototype this create a prototype chain now let’s learn prototype inheritance we can use the prototype to add properties and methods to a Constructor function and objects inherit the properties and methods from a prototype let’s see the previous example of Constructor function so this is one Constructor function with two parameters and the two properties first name and last name now previously we were adding like person one that is one object and in this object we can add new property like this person. AG so it will add a new property in the person one object but here we want to add one property in the Constructor function like we have the person Constructor function so we cannot add one property like this in the Constructor function and we cannot add a method in the Constructor function like this after Declaration of the Constructor function we cannot add the extra Properties or method like this to add the another property or method in the Constructor function after declaring we can use the Prototype here we have only two property in this Constructor function so let’s add one more property so to add one property in this Constructor function we will add the function name person then prototype like this and in this prototype we will add one new property name so let’s add the property name gender and the value is male so using this we can add one new property in the person Constructor function now let me create object also so I will use the const keyword and object name so the object name is person one and create an object using new operator and the function name and pass two values and we will create one more object so duplicate this it will be person two and different value so we have two object person one and person two now let’s see whether the newly added property is available in the person one and person two or not so let’s add console.log person one object and and see the output in the console tab here it is displaying first name Elon last name musk here we have only two properties but we have added the another one gender which is not available here but if I expand it and come to the Prototype here we have the Prototype and open this prototype here you can see our newly added property gender male in this prototype so you can see how you can add a new property in the protot prototype and this prototype property will be inherited by all the object now let’s see the output for the person one. GN Zender and see the output it is displaying male because the object is inheriting the properties of the Prototype now let’s see the output when we access the person two for the second person object let’s access the Ender and you can see it is displaying name male again here we have added gender property in the person Constructor function using prototype and this person one and person two objects inherit the gender property from The Constructor function prototype gender property is not available in the person one and person two object you can see in the console but still we can access it because it is added in the Prototype which is here now let’s see how to add one method in the Constructor function so here we have added one gender property so instead of this we will add one method let’s add method with the name get full name and this method will be a function definition so in this function we will return the full name so write return this DOT first name and space this dot last name so in this person Constructor function we are adding one method using the Prototype and this method name is get full name this method will return the first name and last name of the person so let’s see the output of the person one in the console tab you can see it is displaying first name and last name in this console but if I expand it here you can see we have the Prototype and if I expand this prototype you can see in the person one prototype it is displaying get full name method you can see the get full name method is here so this get full name method is not added in this person one or person two this person one and person two object is inheriting this method from the Prototype of the Constructor function so we can access it like this get full name person 1.g full name let’s see the output it is printing Elon Musk now we can access this get full name from the person two also and see the output it is displaying billgates let’s understand this example again here we have created one Constructor function with only two properties after Declaration of the Constructor function we cannot directly add new property or method in this function but to add the new property or method we will use the Prototype so we are adding person. prototype and the method name method is a function declaration so we are adding function and this function will return the first name and last name now here we are creating two objects with the Constructor function person one and person two now this person one and person two does not have the get full name but still we can access the get full name method from person one and person two because it is inheriting the Prototype of the Constructor function so we can access person 2.get full name and we can also access person 1.g full name now let’s see what will happen if I change the Prototype value so let’s create one Constructor function here we will add one property Elon mask and in this one we will add one new property using prototype so we will add person do prototype and the new property name age is equal to 25 so we have added one new property in the Prototype that is age is equal to 25 now we will create one object so to create an object we will use the const keyword and the object name it is person one and new then Constructor function so this will create one new object that is person one so here we have created one new object called person one after creating this object let’s change the value of this property so in the next line we will add person do prototype is equal to age 52 like this earlier we have added age 25 and here we are changing the Prototype property age 52 so after changing again we are creating one new object const person two new and Constructor function so before changing the property we have created one person one object and after changing the Prototype we have created person two object now let’s see the output in the console tab so we will add log person one and person two and you can see it in the console tab it is displaying name Elon Musk in both object but if I try to access age and age in the second object so you can see the output for the person one it is displaying is 25 and for person two it is displaying is 52 because if a prototype value is changed then all the new objects will have the change property value and all the previously created objects will have the previous value so in this example you can see here we have the property value 25 and created one object person one in this person one object A’s value will be 25 and before creating person two we have changed the property so this person two will have the updated property value that will be 52 that’s why it is printing 25 for the person one age and 52 for the person 2 Age so this this was all about JavaScript prototype in this tutorial you will learn about object destructuring object D structuring in JavaScript is a feature that allows you to extract the properties of an object into variables this can be useful for assigning the properties of an object to variables in single statement let’s understand it with one example we will add one object with the name person here we have created one person object with two properties first name and last name to aore these properties value in a variable we used to write person DOT first name this is for accessing the first name of this person and to it in variable we used to write let and one variable name like f name is equal to person. first name like this if I want to store the last name we will add another variable name L name Person dot last name so this is the previous syntax to store the object properties value in a variable but es6 introduces the object D structuring syntax that provides an alternative way to assign properties to an object variables here is the Syntax for object D structuring we will add L and in this curly Braes we will add property name and value another property name and value and here we will add the object name that’s it so let’s assign the properties of this person object in variables using the object D structuring here we will add person and here we will add the property name so the property name is first name and this first name will be stored in the variable called f name now add one comma and write the another property name and for this property name again we need one variable so the variable name is last name so this is the simple syntax of DS structuring we can write the property name and value to store the object properties value in variables now if I check the value stored in this F name variable or L name variable we will just add log F name you can see it is displaying alone if I I add L name here will be capital n and you can see the output musk we can further simplify this syntax suppose you want to add the variable name same as the object’s property name like object property name is first name and last name and our variable name is also first name and last name then here we don’t have to write the variable name just write first name and last name and then object now to print this we will add console.log first name it is printed here in this console now let’s add last name you can see the last name in this console so this is the simple syntax of object destructuring here in this object we have only two properties but what will happen if I add one more property in this object destructuring syntax let’s add one age that is not available in this person object then what will happen let’s see the output if I add console.log age it is printing undefined because this age property is not available in this person so when you assign a property that does not exist in an object to a variable using the object D structuring the variable is set to undefined now in this object D structuring we can add the default values also suppose here we don’t have the age value so we can add like this age is equal to 18 so this is the default value of the age variable if the property is available in this object it will display the actual value and if it is not available it will display this default value 18 so you can see the output it is displaying 18 because the default value for the age is 18 now suppose this age is available here in this object we are adding age 52 now what will be the output you can see the output it is displaying 52 because it will ignore the default value here we already have age declared in the person object so this age variable will store the actual value of the property which is 52 so this is all about object D structuring now let’s learn about object literal syntax extensions in es6 to create one object we used to write like this const person and first name and last name so this is the object literal syntax to create an object with the key value pairs but here if I typ one variable let first name equal to Elon and last name m here we have two variables first name last name so we can simply add first name comma last name we don’t have to write the key values in this object we will simply add the variable name and this person will store this information as key value pair now if you try to print this person let’s add console.log person you can see it is displaying first name Elon last name musk so we are just adding the variable name in this person object and this person will store the variable name and value also as a key value pair so this is all about objects in JavaScript in this video we will learn about JavaScript class classes are one of the feature introduced in es6 version of JavaScript JavaScript class is a template for creating objects to create a class we use class keyword then we write the name of the class within the class we create one Constructor method you should always add a method with the name Constructor within the class the first letter of the class name should be in capital letter JavaScript class is similar to the JavaScript Constructor function to create a Constructor function in JavaScript we use to write function and name of the function I’m adding person in this function we will add here we will add the code to initialize the property value of an object after creating the Constructor function we create object we can write any object name person one new keyword and Constructor function and pass two values here so this is for creating one new object to display the object created using this Constructor function we used to write console.log person one you can see the output in this console tab it is displaying one object with the property name and age now we can create the object using class also so now let’s create the class to create a class we use to write class keyword then class name I’m adding the class name person and in this class name we have to add one Constructor method and this Constructor method is used to initialize the value of the object so let me add this here here we will add two parameters so this is one class with the name person and this line will create one object with this class now let’s duplicate it we’ll create another object with the name Person two and we will pass another value so we have two objects person one and person two now if you want to display the object in console tab you can write console.log and you can see the output it is displaying here one object with two properties name and age and the name is Elon Musk and age is 52 now let’s print second object which is person two you can see the output in the console tab it is displaying another object object with the name billgates and age 67 this Constructor method initialize the property of the object JavaScript automatically calls the Constructor method when you create an object using the class now let’s learn about JavaScript class methods we can add any number of methods in JavaScript class so let me remove this second person and in this class after this Constructor we can add any method so let’s add one method with the name greet and this greet method will return text hello this do name it will return hello and name of the person now I want to display this person one object so here I will add console.log person one and in the console tab you can see one object with two properties name Elon mask is 52 now let’s expand it and here you can see prototype and in this prototype you can see this GRE method in this prototype of the object so we can call this GRE method from this person one object so in this console.log I will add G and you can see the output it is displaying hello Elon Musk because we are calling the Greet method from the object and this greet method is returning the text hello and the name so that’s why it is displaying hello Elon Musk we can add any number of methods so let’s add another method here here I will add a new method change name this change name method will update the name of the person in the object so here we will add new name and then this do name is equal to new name so in this method we are adding one parameter so when we will call this method we have to pass one argument let me remove this console.log and here I will call the change name method on person one object so just add person one dot change name and we have to pass one argument so let’s add a new name I will add my name here AAS now we can print the object let’s add console.log person one you can see one object name aenas age 52 now if you want to print the name only here we will add person 1. name it is printing the name in the console tab so in the JavaScript class you can add any number of method now let’s learn about gets and Setters in JavaScript Getters and Setters are a special methods in JavaScript that allow you to control how properties are accessed and modified they are defined using G and set keyword now let’s understand the getter method a getter is a method that is called when a property is accessed it can be used to do things like validate the value of property or convert it into different format so let’s see this example here we have one class with only one method great and this method is returning hello and the name here we have created one object using this class this code will call the Greet method from the person one object and display the return value in the console so while calling this great method we used to write this parenthesis but when we clear it as a geted method so here we will add get space and the method name that’s it just add the get keyword and after that here you don’t need to write the parenthesis simply add gr person one. greet and save the changes you can see the output it is still displaying the message hello Elon Musk so we have just added this get keyword in front of this method name and we can call it directly without adding parenthesis now let’s understand the seter method with one example here we will change the method I will add change name new name this do name is equal to new name to call this method we need to write person one dot change name and pass one argument like this but here we will add set keyword in front of this method just add set then we don’t need to write this parenthesis and pass the argument simply we will add person one do Setter method name and assign one value using assignment operator like this and see the output here I’m displaying the person one object it is displaying one object and name is AAS age 52 like this so we add this set keyword to Define one Setter method we can call this method on object and assign one value with assignment operator a Setter is a method that is called when a property is modified it can be used to do things like update the value of the property or perform some other action we can use the same method as getter and Setter let’s see one example let me change the method name it will be person name name and here I’m adding set now we will add get this will be getter method and I’m adding the method name same as the setter method here also person name and this will return return this dot name so you can see here we have declared one class in this class we have one Setter method and one getter method and both method name is same person name and person name now to call this getter method we’ll simply add console.log person one do person name so it will return the name of the person you can see the output it is displaying the name now we can update the name using this Setter method so let’s add person one dot person name and just assign one value after that again we will call this get method that will displ play the name so you can see the output first it is displaying the name Elon and after that it is displaying the name ainash so we have the same method name as getter and Setter to call the getter method we are simply adding the object name and Method name and to call this Setter method we are adding object name and Method name and assigning one value that’s it when we assign any value it will call the setter method and update the properties value let’s learn about JavaScript class expression a class expression provides you an alternative way to define a new class it is similar to a function expression but it uses the class keyword instead of the function keyword class expression can be named or unnamed if they are named the name can be used to refer the class later if they are unnamed they can only be referred by the variable that they are assigned to so let’s define one class expression we will add the class keyword in this class we will declare one Constructor method this Constructor method will initialize the object property property name is name here we will add name and in this class we will add one method method name is get name it will return the name now we will assign this class in a variable let’s add let keyword person is equal to class A Class expression does not require an identifier after the class keyword you can use a class expression in a variable declaration now we can create an object so let’s add cost person one new person we can refer this class with this variable and here we will add one [Applause] argument now we can display our object in the console tab so let’s add console.log person one you can see the output in this console here we have one object with the name Elon Musk so this was the class expression in JavaScript in this video we will learn about JavaScript class inheritance JavaScript class inheritance allows you to create a new class on the basis of already existing class using class inheritance a class can inherit all the methods and properties of another class inheritance is a useful feature that allows the code reusability to create a class inheritance we use the extend keyword so let’s create one class write the class name Person add one Constructor method and add one method GRE console.log hello and name here I have created one class now I will create another class that will inherit all the methods of the person class so here we will create another class and the class name is a student then write the extends it will extend person so we are creating another class with the name a student this a student class will inherit all the method and properties from this person class in this new class we have not added anything but let’s create one object here we will add con student one this is the object name is equal to new student and we have to pass one value Peter so we have created one object with the name a student one and we are passing one value in this student but this student don’t have the Constructor and here we have added extends keyword so it will inherit all the method of this person class and it will pass this page Peter here in this Constructor and the name will become Peter and we can also call this greet method so let’s try to call this greet method we’ll add a student one do greet you can see the output it is displaying hello Peter so this property name is available in this person class this method is also available in this person class but we are creating the object object with the a student class and calling this method from the object of a student class so we can call the method and properties of the parent class it means a student class is inheriting all the method and properties of the person class now let’s learn about JavaScript super method the super method used inside a child class donates its pent class in this student class let me create one Constructor add one parameter and in this Constructor we will call Super here this super method inside the student class refers to the person class when we create one object using the student class it will call this Constructor method automatically then it will call this super and then the super will call this Constructor from the parent class which is person class and pass this name here in this Constructor then the argument will be stored in the person’s name still it will display the same output you can see in the console hello Peter let’s understand this example again here we have created one person class and we have another class with the name student and this student class class inherits the property of the person class so this is the parent class this is child class in this child class I’m adding super so this super refers to the parent class which is person class and it will pass this argument in the pent class so this was the Super method in JavaScript now let’s understand what is Method or property overwriting or ping method suppose the parent class and child class has the same method or property name in this case when we call the method or property of an object of the child class it will override the method or property of the parent class this is known as method overriding or cying method let’s understand the method overriding with one example here we have the parent class and this is the child class in this one let’s create the same method greet and in this greet method we will add console.log hello student plus this dot name and in this one we will add hello person this do name so you can see in this parent class and child class we have the same method name which is GRE in the parent GRE it prints hello person and name and in child class this greet method prints hello student and name now if we call the Greet method from the object created using child class then it will call the method of the child class you you can see the output in the console tab it is displaying hello student Peter it means it is calling this greet method from the child class so the method of the child class override the method of the parent class this is known as method overriding now let’s learn about JavaScript static methods static methods are bound to a class not to the instance of the class you cannot call the static method on an object it can be called only on the class so let’s declare one class class name is person and in this one let’s declare one method this method will display only text hello on the console now in front of this method if I add static it will become the static method now we cannot call this greet method on the object created using the person class we can call this greet method only on the person class let me make it capital P here the name of the class should just start with capital letter now let’s create one object here we will add const person one is equal to new person Peter and if I try to access the GRE method from the object object name is person one dot GRE it will display one error you can see the console tab it is giving an error now if I add person. greet I’m adding the class name and greet you can see the output here it is displaying hello now if you want to use these object properties inside this static method then you can pass the object as a parameter so let’s take another example here we have the person class then we have the St method in this a static method we will add one parameter X and in this console.log I will add hello space X do name so it will display the name from the object now we can call this greet method from the person class and we have to pass the object let’s pass this person one object here and now you can see the output it is displaying hello Peter because here I’m adding hello then object then property name so from this person object it will get the property name name is equal to name so the name will be Peter and here I’m adding text hello so hello Peter is printed in this console so this is the static method in the JavaScript now we will learn about JavaScript private methods private methods are accessible only within the class it means we cannot call the private methods outside of the Class by default methods of a class are public to make a method private we need to start the method name with the hash tag so let’s take one example I will add class person Constructor first name and last name we have two parameters this DOT first name will be first name then this do last name it will be last name now let’s create one method in this class method name is full name and it will return this DOT first name then a space this do last name so it will return the full name now let’s create one object using this person class I will add const person one is equal to new person and here we have to pass two argument Peter and let’s add anything B so we have created one object with the name person one now let’s see if I add person one dot full name we can call this method right and it is returning one value so we can add console.log person. full name you can see the console tab it is displaying Peter V it is returning the full name now if I add hashtag here so this method will become private method now we cannot access this private method outside of this class you can see the output it is giving an error now let’s see how to access this private method inside the class so in this class only we will create another method let’s create one method called display here we have display method and within this display method I will add console.log and here we can call this method but to call this method we have to add this this dot full name this will refer to the object and this is the private method with the hashtag now we can call this display method outside of the class so simply add person one 1. display and it will display the output here in this console tab it is displaying Peter B so let’s understand this example again here we have declared one class with the name person in this one we have this Constructor that will initialize the object properties then we have this private method and this method name I have added has tag that’s why it becomes private method now we cannot call this private method outside of the class we can call this method inside of this class so within this class we are calling this method here and to call this method within the class we need to add this keyword this dot method name with the hashtag so like this we can call the private method within the class now let’s learn about private static method this is the private method now we can can add the static keyword like this so it will become private static method and we cannot call the static method on the object we can call the static method only on the class so here we have to pass one object while calling this method so here we are calling this method so in this one we will pass the object so we will refer the object with this keyword we will pass the object and here we will add one parameter and from this parameter it will get the first name and last name it means it will get the first name and last name from the object that we are passing through this keyword while calling this private static method now you know we cannot call this a static method on the object we can call it on the class so instead of this keyword we will add class name person person dot has full name now you can see the output it is displaying Peter B let’s understand this example again here we have declared one class in this class we have one static private method now to call this a static private method we will use the class name dot method name with the hashtag and to get the object’s properties we are passing the object as argument here we are calling display method from the object this display method will call this class and this static method that is a static and private method so we can access the estatic private method using the class name person now we have completed class in JavaScript now we will learn about document object model the document object model is an API for manipulating HTML documents the Dom provide functions that allow you to add remove and modify part of the document effectively the Dom represents an HTML document as a tree of nodes in this HTML code you can see this is the node this HTML tag is a node this head tag is also one node this title tag is a node this text Greatest Tag is also one node this body tag is a node this comment is a node and this P tag is also a node now let’s understand about the node type so this one is the document type node these HTML head title body these are the element type node and these text are the text node and this is the comment node now let’s learn about node relationship any node has relationship to another nodes in the Dom tree and it is same as described in the traditional family tree for example this body is the child node of this HTML node and this HTML node is the parent node of this body node this body node is the sibling of this head node because they share the same immediate pent which is HTML element now let’s add some other content within this body here we will add one div and add this P tag within this div let’s duplicate this so we have four P tag in this div so this div element is the pent node of these P tag and the P tag is the child node of this div this one is the first child and this one is the last child the second p is the next sibling of the first one this third p is the next sibling of the second one and the fourth one is the next sibling of the third one in same way you can say the first one is the previous sibling of this second P the second p is the previous sibling of third p and the third p is the previous sibling of fourth p now let’s learn about selecting elements using Dom to get elements in JavaScript there are various method in Dom so the first one is get element by ID method get element by ID method returns an element object that represents an HTML element the get element by ID is only available on the document object let’s understand this with one example here I will remove this comment and I will add only one text in P tag and for this P let’s add one ID so I am adding the ID message and in this P we have the text JavaScript Dom now let’s add the JavaScript in this HTML page using the script tag within this script tag we can add our JavaScript code here we will add one variable with the name MSG which is message and we can write document dot get elementy ID and here we have to add the ID of this element which is message so this document. get element by ID will select this element and it will be stored in this message variable now we can print it let’s add console.log MSG here you can see the output in console tab P ID message JavaScript Dom so this element is printed in this console because I’m adding console.log MSG so in this MSG variable we have stored this element which is in the P tag if the document has no element with the specified ID then it will return null Suppose there is no element with this ID on the web page then it will return null you can see null and if there is multiple element with the same ID it will return only first element let’s duplicate it and in this one we will only write JavaScript now you can see the output in console it is still printing ID message JavaScript Dom so it will select the first element with this message ID because the ID of element is unique with the HML document the document. getet element by ID is a quick way to access an element now we will learn about get Elements by name method every element on HTML document may have a name attribute multiple HTML elements can share the same value of the name attribute let’s take one example here we will create one input field and in this input field I will add the type radio and we will add one name attribute name will be language and value will be JavaScript we can add another input field with the same name attribute and value will be something else python in this HTML code you can see we have two elements with the name attribute and we can select this element using this name so in this sub script we will add let BTN is equal to document do get Elements by name and in this one we will add language because the the name value is language now we can print this let’s add console.log BTN and you can see the output in the console tab here we have the node list that contains two input field you can see input and input so get Elements by name returns one list of nodes now we will learn about get Elements by tag name the get Elements by tag name method accepts a tag name and return a live HTML collection of elements so let’s understand it with one example in this HTML we will add one title in H1 so the text is first heading let’s duplicate it this is second this is third this is fourth we have four text here in the heading tag now we can select the element using the tag name which is H1 so here in this sub script we will add one variable with the name heading is equal to document dot get Elements by tag name and here we will add the tag name which is H1 now we will print it using console log heading so you can see the output on the console tab it is returning the collection of four HTML elements you can see H1 H1 H1 four times so this get Elements by tag name return the collection of HTML elements now we will learn about get Elements by class name the get Elements by class name method returns an aray like of object of the child elements with a specified class name the get Elements by class name method is available on the document element or any other element also so let’s understand it with one example here we will add one class name in the first title so the class name is message in the second one we will add the class name message and in the third one also we will add the same class name message let’s delete the fourth one now we can select these elements with the class name in this script let’s add let MSG is equal to document dot get elements by class name and here we will add that class name which is message now we will check the output in console MSG and you can see the output here it is returning the collection of three HTML element with the class name message you can see H1 do message H1 do message H1 do message so it is returning all the HTML elements with the same class name now let’s come back to the code and here we have added document. get Elements by class name we can add this get Elements by class name on any element also so let’s see the example here I will add one div and insert these two title in this div and for this div we will add one ID let’s add the ID container so total we have three headings with class name message but these two headings are included in this div with the ID container now we will add the get Elements by class name over this container so we have to store this container in one variable so let’s add let cont is equal to document do get element by ID and the ID is container now we can write cont here in sh of document we will add cont which is container and get Elements by class name now it will only give the elements within this container you can see the output here we have only two elements HTML collection 2 we have two HTML elements in this collection H1 do message H1 do message so this get Elements by class name will return the collection of HTML elements with the same class name on the document or within the element now let’s learn about query selector and query selector all method the query selector method allow you to select the first element that matches one or more CSS selector the query selector is a method of element interface we can apply this on element also here we will add one variable let MSG is equal to document dot query selector and in this query selector we have to add the CSS selector so in CSS to select this title we used to write Dot message because it’s a class name so we used to write do message to select this element in the CSS file so we have to add the same thing here we have to add the CSS selector in this quy selector that’s it so here we will print console.log MSG so first let’s see the HTML code here we have one title with this message another title with this message and third title with this message so total we we have three title with this message class name now let’s see the output in console tab here it is displaying only first element H1 class name message first heading so let’s come back here you can see we have added query selected only so it will return only first element now we will add query selected all after adding query selected all you can see it will display all the elements we have node list of three element which is H1 message H1 message and H1 message so it is returning all three headings and if I remove this all and write query selector only it will only return the first element here we have added quy selector all on document we can use the quy selector all on any element also so let’s add cont for container is equal to document do get element by ID here we will add this ID container now we will add this query selector over this container so just add container do query selector so it will give only two elements which is here second heading and third heading now you can see the output in console tab here it is displaying node list 2 it is displaying Two element so it is selecting only two elements which is in the container with the class name message now let’s come back to the previous example document do query selector all now let’s see what we can add in this query selector so we can add the class name using Dot so we can add the ID also we will add the ID and we can write this container we will add hashtag and this container because we used to write like this for CSS selector hashtag container because here we have the ID container so we can add the hashtag to select the element with the ID now we can add like this directly div so it will select this div element if we just write H1 so so it will select all the heading element with H1 tag we can write like this also div and H1 so it will select the heading within this div you can see the output here we have 2 H1 only now come back and we can select the multiple element like this div also and H1 also so it will select all the div element and all the H1 element by adding one comma you can see here we have four element node list four one is div with the container ID and three H1 tag with the class name message so basically we can add all the CSS selected in this query selector and query selector all method now we will learn about traversing elements to understand how to get the pent element how to get child elements and how to get the siblings of an element to get the parent node of the ESP specified node in the Dom tree we can use the parent node property in this body let’s create some HTML elements We’ll add one div with the ID title and within this div We’ll add one text NP tag welcome to greatest tag and for this P let’s add one class name text so we have one parent element and one child element now we will try to get the parent element using this child element so here in this script we will add let txt is equal to document dot query selector and we will add dot T text so it will select this P element now we have to get the parent so we will add console.log then txt which is the child element dot parent node this one just add this parent node and it will display the parent element of this child element so now let’s see the output in the console tab here you can see it is displaying div class title which is the pent element now let’s learn how to get the child elements we will learn about how to get the first child Element last child element and all children of the a specified element so here we will add another example just remove it and within this let’s create multiple P tag we have four text here Greatest Tag one two three and four so we have four title welcome to greatest tag 1 2 3 4 so now we’ll get the child element using this parent element now Within in this script first we will select this parent element so let parent is equal to document do query selector and write the query selector title so it will select the div now we have to get the first child last child and all the children of this div so here we add console.log and this parent then we will add first child now you can see the output in console tab here it is displaying # text because here we have some space so so this space is also one empty text node if we remove this and write it in the same line now you can see the output in console tab it is displaying the first title which is welcome to greatest tag one and if I add a space here it will display one text node now I want my text like this and I want to display the first element so here we will just just add first element child like this parent. first element child now you can see the output it will display the first element welcome to greatest tag one the first title in P tag similarly we can add last element child like this and see the output it is displaying well welcome to greatest tack 4 right so it is giving the last element which is welcome to greatest tack four now if you want to get all the child elements just add child nodes that’s it after adding this come back to the web page and here you can see we have node list text again P again one text again P so we have the empty text node then P tag let’s come back and here if I remove this a space and write everything in the same line like this now you can see it will only display four element which is 4 P element so we got the child nodes of this div now we will learn about how to select the next sibling and previous siblings of an element so in this example in this second P tag we will add one class name let’s add class name second like this so it’s easy to select this element and according to this element we will find the previous siblings and next siblings so here we will add second here also second so it will select this welcome to Greatest Tag 2 now to get the previous sibling here we will add this element then Dot and write previous element sibling that’s it you can see the output it is displaying welcome to greatest tack 1 so we are finding the previous sibling of Welcome to greatest tack 2 now just come back and here we will add next so it should give this welcome to greatest tag three because we are selecting this second one and we are adding next siblings so it will display third now let’s see the output H is dis playing Welcome to greatest Attack 3 so this is how you can select the previous siblings and next siblings now let’s learn how to manipulate the HTML elements so the first one we will learn is create element to create an HTML element we use the create element method the document. create element accept an HTML tag name and return a new node with the element type so let’s understand it with one example here we can add document dot create element and in this one we have to add one HTML tag so let’s add the div tag so it will create one div element we can store it in any variable so we’ll add let div is equal to document. create element div so it will create one div element now we can print it let’s add console.log div you can see the output on the web page it is displaying this div this div is empty right now so let’s come back here in the next line we will add div div dot inner HTML we will learn inner HTML also so here we can write any HTML code we will add one P tag and in this P we will add welcome to greatest tag and close this P now we’ll see the output here you can see one div and here we have one text in this we have one div tag and within this div we have P tag and the text is welcome to greatest tag so you can see using this document. create element we can create One D element or any HTML element and we can add any HTML code within this element and we can print it and we can also add this element on our web page so to add this element on our web page here let’s add document dot body we will add this element on the body so here we will add body dot app and child we will learn the app and child later so to insert this newly created div in this body we are adding appen child div so after adding this come back to the web page you can see we have text here welcome to greatest tack right so this is added us using this appen child div that we have newly created within this body you can see we have not added any text in div or P tag we are creating this element using this document. create element if I change it welcome to greatest tag two you can see it will be deflected here welcome to Greatest Tag 2 now we can add the ID or class name anything in this newly created element so here let’s add div. ID is equal to title let’s see here we have this div with the ID title now we can add the class name also just write div. class name title and you can see the output here D class title so we can create a new element using document. Create element and we can add the content here we can add the ID we can add the class name or any other attribute next we will learn append child method we use app and child method to add a node to the end of the list of child nodes of a a specific parent node the append child can be used to move an existing child node to a new position within the document so let’s create some HTML elements here here we will add one UL tag with the ID menu so we can easily select it here we will add some content in lii home second one is about third one is blog right you can see these elements on the web page home about blog let’s come back let me add one more here we will add project now within this script we will add let menu is equal to document do get element y ID and the ID is menu so it will select the UL element now we have to create one element and we will add that element in this UL so here let’s add let list is equal to document dot create element and the element tag name is is lii so it will create one lii element and its name is list so in this list we will add inner stml and through this inner HTML we will add one text contact like this now we can use menu do appen child list so this is the element which is here ul and this epen child will add this list at the end of this list in this list we have home about blog project so it will add the newly created list item after this project so here we have created one list item and the text is contact so this contact will be added after this project you can see on the web page here we have home about blog project and after this project we have contact that we have created using this create element and added using appen child in this UL so this newly created list will be added at the end of this list next we will learn about text content to get the text content of a node and its descendants you can use use the text content property so let’s see one example here we have the same HTML elements and this a script we have added this line that will select this UL element and after that remove this and here we will just add console. log menu so it will display the complete menu in the console tab now we just want these text so here we will add menu dot text content that’s it menu do text content and see the output in the console tab here it is displaying home about blog and project so it will ignore the HTML tag and display only text now let’s see one more thing here if I write inner text we are adding inner text and see the output still it is displaying home about blog and project but there is one difference this inner text is following the CSS also in this last one if I add a style display none so it will be hidden from the web page you can see that is not visible so this inner text will return only visible text you can see here we have home about blog and these home about blog is here on the web page but we have one more element here project which is invisible but if I write text content it will display all the HTML text content you can see on the web page we have home about blog only but here it is displaying home about blog and project so this text content is displaying all the text inside that element and inner text is displaying visual text only now we can use the text content to insert the text also let’s add menu dot text content is equal to hello so in this menu right now we have these list so it will remove this list and it will add hello let’s see the output here you can see we have only Hello in this web page so we can read and add the text using this text content on the web page next we will learn about iner HTML so inner HTML is used to add the HTML code on the web page so here we have added textt content so instead of this we will add inner HTML and see the output on the web page you can see we have hello so it is in the normal text so here if I write H1 it will add this hello text in heading so so it is in heading style hello so this inner HTML accept the HTML tags and add the text on the web page but instead of this inner HTML we will add text content now you can see what will happen it will add this as a plain text H1 is also displaying here and if I add in our HTML it will add this text and this hello text will be in the heading Style you can see this hello text on the web page next one is after method we can use after method to insert one or more nodes after the element so this is the Syntax for after method we have to add the element name then after method and we have to pass a new node that we want to add after that particular element suppose we have this menu element so we can write this menu then after method in this one we can pass a new element and we can create a new element using the create element method this after method can accept multiple nodes so we can add multiple element after this menu it can also add a string after the element so we can add multiple string s str1 s Str 2 like that we can add multiple string after this menu element so so this is the use of this after method now let’s learn about append method so this append method is also similar as append child but in the append method we can add multiple elements this is the Syntax for append methods we have to add the parent element then append then we have to pass a new element that we want to add in that parent element so this new node or new element will be added in the parent element at the end of the list of childs so what’s the difference between append and append child so this appen will accept multiple nodes and it can add string also the next one is prend Method so this is the Syntax for prepend method parent node. prepend and new nodes so it will add the new node as a first child in this parent node so this is the prepend method the the next one is insert adjacent HTML so this is the Syntax for insert adjacent HTML here we have to add one element then insert adjacent HTML method and here we have to give position and text so suppose we will add this element menu and we want to add one text at the end of this list so here we have to give the position so the position can be before begin after begin before end and after end so suppose we add before begin so this element is starting from here so this before begin position means it will add the new node before this ul and if we add after begin it will add it here at this position and if we add position before end so this is the end so it will add before end here it will be added in this line and if we add after end so it will be added after closing of this UL so let’s test it here we will add any one position I will add before end let’s add before end and here let’s add lii contact like this so here I’m adding one html text and this is the position and this is the element where we want to add this so you can see the output on the web page the contact is added here now let’s come back and if I add after begin so it will be added here at this line because this is a starting of this element and it will be added here you can see the first one is contact and after that home so this is how this insert adjacent HTML works now the next one is replace child here is the Syntax for the replace child method replace child method is used to replace the child element with the new one so we can use this syntax we will add the parent node then replace child method here we have to add the old child that we want to replace and here we have to add a new child that will be replaced on the place of old child next one is clone node method we can use clone node method to clone an element here is the Syntax for clone node method we will add the original node then clone node so this new node will have the another copy of this existing node if I add menu so this new node will have one copy of this menu element let’s print this one here we will add console.log new node you can see the output it is displaying ulli menu now let’s come back and here we can pass the argument so if I WR true it will clone this descendants also this UL element and these Li elements Also let’s come back you can see we have ul and all these Li and if I remove it or write false by default it is false we don’t need to write but if I write false you can see here we only have UL element and if I remove move it still it will be only ul and if I write true it will clone the element and all the child element also you can see ul and all three lii so this is the Clone node method next one is remove child method to remove the child element of a node we can use remove child method here is the Syntax for remove child method here we have to add the pent element and then write the element that we want to remove from the pent element so here let’s add menu and from this menu suppose I want to remove this last one so here we will add menu dot last child element so it will remove this blog you can see on the web page here we have home about blog is missing if I write menu DOT first element child so it will remove the first element which is home you can see on the web page here we have about and blog so this is the remove child method next one is insert before method we can use insert before method to insert a new node before an existing node as a child node of a parent node here is the Syntax for insert before method we have to add one pent element then this insert before method and it will accept two arguments in this one we have to add the new element that we want to add and we have to add the existing element before that existing element this new element will be added we have the pent element menu so we will add menu here and we want to add the new element before this lii that home link so here we’ll add menu DOT first element child so this new node will be added before this home so this is the insert before method so these are the methods to manipulate the HTML elements now we will learn about attribute methods so let’s understand what is attributes here I will add one HTML element input type is text we will add one ID so let’s add the ID username and we can add the placeholder also username so in this HTML tag we have added three attributes which is this one this one and and this one this is the attribute name and this is the attribute value the ID is the attribute name username is the attribute value this placeholder is the attribute name and username is the attribute value now how we can get the attributes of any HTML element using JavaScript so let’s add one script tag here where we will add our JavaScript code first we have to select this element so we can use any method to select the element let input box is equal to document. get element y ID I’m using get element by ID method and we will add this ID username after selecting the element we can find the attributes available in this HTML element so to get the attribut we will just add the element which is input box and after that just add attributes that’s it it will give all the attributes available in this HTML element so to print this in console we will add console. log and add this code inputbox do attributes after writing this let’s come back to the web page and uh you can see the console tab it is displaying type then ID then placeholder so we have three attributes in this HTML element now we have some attribute methods to get the attribute value and to set the attribute of any HTML we can check for some attribute whether it is available or not and we can also remove the attribute using the attribute methods so let’s see the first method which is get attribute so instead of this we will add the element which is input box and here we will add get attribute and in this get attribute we have to add one argument so we will add the attribute name so here we have the attribute name type so just add type like this and after that let’s come back to the web page you can see here is displaying TT so we can read the value of the attribute using the get attribute method let’s take another example here I will add this placeholder write this placeholder here now it will display the value written in this placeholder attribute so come back to the web page here you can see it is displaying username this username text is available in the placeholder attribute so this was the first method get attribute to read the attribute value now we will learn about second method which is set attribute so let’s remove this one here we will add the element which is input box on this input box we will apply set attribute and the set attribute will accept two argument so the first argument will be attribute name and the second argument will be attribute value like this here we will add the name comma value like this so let’s remove this here and here we will add any attribute name so let me add the class so the attribute name is class and here we will add one value let’s add the class name user like this so it will add one attribute which is class and the value is user now to see the updated input let’s add console.log and here we’ll add input box so it will display this complete element on the console so let’s come back to the web page here in this console you can see we have the input element with the type text ID username placeholder username and there’s one more attribute which is class user that we have added using this input. attribute class user so this was the set attribute method now we will learn about next one which is has attribute so it will tell us whether this attribute is available on the element or not it will result in true or false so here we will add another example we will add the element input box then has attribute and this will accept only one argument so in this one let’s let add class and it will return one true or false value so we can directly print this one so just add console.log input box has attribute class so you can see in this input field we have the type ID and placeholder we don’t have class here so it should return false let’s see the output you can see it is displaying false now let’s come back and instead of this class we will add ID so it will return true let’s come back to the web page you can see it is displaying true in this console so this has attribute will return true or false value if the attribute name is available in the input field it will return true if this attribute name is is not available in the input field then it will return false so using this has attribute we can check the availability of that particular attribute on the element next we will learn about another method which is remove attribute that will remove the attribute from the element so in this one we will add element then remove attribute and in this remove attribute we will add one attribute name that we want to remove so here we have type ID and placeholder so let’s try to remove this placeholder just copy this one paste it here so this remove attribute will remove this placeholder from this input element now we will just print this input element in the console we will add console.log input box and now we will see the output in console here we we have the input element and in this input element we have type text ID username but here we don’t have the placeholder because in this code we have added remove attribute placeholder so it will remove this placeholder attribute from this element so these are all four attribute methods now we will learn about manipulating elements a style to manipulate the style of the element we have the property called Style and we can use this a style property to get or set the inline style of an element so here we have the HTML element which is input and in this one we don’t have any inline style so let’s add one style here and here we will add the background color value is red and let’s add one more CSS property here that will be for font size 20 pixel so in this HTML element we have added the inline CSS in this one we have added the background color and font size now to get these inline CSS we can use the style property on this element so here let’s add the element which is input box do style so it will return the CSS properties available in this input field in the inline CSS it is returning some value so we can add console.log and this code now you can see the output in the console tab in this console you can see it is displaying background color and font size because here we have only two inline CSS properties which is background color and font size so this element do style will return the inline CSS available in the element now if if you want to return the background color value or the font size value then we can write input box style dot background color like this after adding this come back to the web page here you can see it is displaying red background color value is red now if you want to see the value of this font size here we will add font size and you can see the output here in the console tab it is displaying 20 pixel so we can get the property name also and value also now we can use this style property to set the style of the element so let’s add input box and on this input box we will add a style and in this a style let’s add one new CSS property let’s add padding padding is equal to 10 pixel after adding this we will display this input in the console so we will add console.log input box so it will display this input field in the console tab where it will add the padding also so let’s come back here you can see we have this input element in this one we have the style background color then font size and after that you can see this padding let’s select this one here you can see padding and the padding value is 10 pixel so using this style property we can get the inline CSS and we can also set the inline CSS now we have one more option to add the inline style in the HTML element that is using CSS Tex text so here we will add the element then style then CSS text and in this CSS text we can add the CSS so let’s add width 200 pixel after adding this let’s print this element in the console you can see the output here on the web page it is displaying this element with the style width 200 pixel here we have only one CSS property which is width 200 pixel let’s come back to the web page we have added CSS text with 200 pixel so it will override the existing inline CSS you can see we already have background color font size but it is not available on the web page why because we are adding width 200 pixel using this CSS text so it will override completely it will remove this and add this one but if you want to keep the existing CSS also and add this one also then you can use the concatenate to perform the concatenate we will just add plus before this assignment operator like this after adding this again come back to the web page now you can see in this input field we have the multiple CSS properties which is background color then we have font size and width also so after adding this concatenate we can use the existing inline CSS also and we can add a new inline CSS using this CSS text we can add multiple CSS properties at the same time you can see we have added width so we’ll add more CSS properties just add semicolon and add another CSS property let’s add height height will be 100 pixel now we will come back to the web page you can see height is also applied in this input field you can see it in the console also here we have height 100 pixel so using this CSS text we can add multiple CSS properties in the HTML element as a inline CSS so this was the use of CSS text for modifying the inline CSS of the HTML element now we will learn about get computed style method currently we have learned how to modify and get the inline CSS properties of the HTML element using JavaScript now how to get the CSS properties written in the external CSS so let’s remove the CSS from here remove this inline CSS and we will add the CSS properties in this head here we will add style tag within this style we will add the CSS selector input and for this input we will add the background let’s add the background color red and font size 12 pixel so we have added two CSS properties for this input element now how to get these CSS properties to get the CSS properties of this input element we will use get computed style method so let’s see the syntax first this computed style method is a window object so we will add window do get computor style and in this one we will add the element we can add one more argument that will be C element so this is the Syntax for get computed style in this one we will add the element if you want to get the CSS property of the element and if you want to get the CSS properties of the seudo element then you have to add the element and it C2 element and now let’s see the example for this input field so here we will add window do get computered style and in this one we will just pass to the element which is input box now it will return the CSS properties available on this input field so we can print it using console console. log and add this one now let’s come back to the web page to see the console tab here it is displaying all the CSS properties that are applied by default on the element in this one we will find the background color also you can see the background color here and there will be font size also it is here font size so now we can get the value of the particular CSS property so from this input box we will add font size now it will display the value of this font size you can see it is displaying 12 pixel that we have added here in external CSS now let’s add the background color we are adding this window. get computed style then passing this element and from this element we’ll get the value of this background color let’s come back to the web page here is displaying the color now let’s come back in this one we will add one more property let’s add the width of 300 pixel and here we will add dot width then we will see the output it is displaying 300 pixel so using the git computer style method we can read all the CSS properties applied on any HTML element now we will learn about class name property class name property return a list of classes separated by space so let’s take one example here we will add one title in H1 tag so let’s add the text greatest T and and with this H1 we will add one ID to select this element we will add the ID title and let’s add some class name also so let’s add the class main the first class name let’s add one more class name which is message so in this one we have added two classes which is Main and message now to get the class name of this element we will use the class name property of JavaScript so let’s add the JavaScript here in this script tag first we have to select the element so let’s add the variable with the name title and select the element using document. get element by ID and write the ID title after that we will add title dot class name that’s it it will return the list of classes available on this element so it is returning some value then we can print this one in console let’s add console.log title dot class name that’s it now we will come back to the web page now it is displaying the classes available on this element which is Main and message so we have two classes we can use this class name property to add a new class also so let’s come back here and here we will add title dot class name is equal to new so this will add one class name which is new in this element let’s remove this class name here we will display the complete element in the console using this console.log title let’s see the element here you can see it is displaying this HTML element with ID title and class new we have only one class which is new but in this HTML you can see we have already added Main and message so this will override these classes here we have two classes that will be removed and this new will be added in this class but if you want to keep the existing class also and new one also then you can use the concatenate using this plus and this assignment operator after adding this here we will add a space and let’s come back to the web page now you can see the same element H1 here and in this element we have class main message and new so we have total three class here so using this class name we can read the class name of the HTML element and we can add a new class also now we will learn about class list property class list return the collection of CSS classes so let’s see if we add class list and it is returning some value so we will print this one title. classlist like this we are just adding title. class list and you can see we already have Main and message class in this element now we will come back to the web page in this one you can see we have a list where we have Main and message class so we have two classes so this class list is returning the collection of classes available in any HTML element so this was the first use of this class list to display or get the class list of any HTML element now we can use this class list to add the class to remove the class so let’s understand how we can add a new class using this class list so in this title element we will add classlist do add like this we are adding class list do add and in this one we can add a new class just add new like this that’s it after adding this we will display this complete element in console tab we are displaying this title let’s come back to the web page here you can see we have this element with three classes main then message then new let’s change the size so you can see we have total three classes main message and new now let’s come back if I add multiple classes we’ll just add a comma and add a new class name like new two so we are adding another class name like this we can add multiple classes using this class list you can see we have more class name here main message new and new to so using this class list. add we can add a new class name in the stml element now we can use this class list to remove any class so instead of this add just type remove class list. remove and what we will remove we already have Main and message so let’s remove this message write it here in a quote and come back to the web page here you can see in this element we only have one class which is main now just come back and we can remove both classes so let’s add comma and write main so it will remove the another class also we can type multiple class name here and it will remove all that classes from that element you can see this element in this element we don’t have any class we have the class attribute name here but we don’t have any value in this class next we can use this class list to replace any class so instead of this remove we will add replace and to replace this one we have to add the existing class name and new class name so in this HTML element we have message so write message here and we are adding a new class name instead of this message so we’ll add MSG so instead of this message we will replace it with MSG now just come back to the web page you can see the output in console here we have class name Main and MSG so we are replacing this message class with MSG class using this class list. replace place now we have one more option to check whether the class is available or not for that here we will add class list do contains and in this one we will add any class name so this message is here we are adding message so this will return the value either true or false if this message is available in this element then it will return true if it is not available it will return false so we’ll just print this one remove it from here add it in console and come back to the web page you can see it is printing true because this message class is available in this element so we are adding class list do contains and class name this class name is available in the element that’s why it is returning true suppose we add MSG and this MSG is not available in this element then it should return false you can see the output it is false now we have one more thing which is toggle let’s see this example here we will remove this one we will just print this complete element in console and here let’s add title dot class list. toggle and in this toggle we can add any class name suppose we add message what will happen if this message class is available in the element it will remove it this toggle means if the class name is available it will remove it and if it is not available then it will add that class name in the element so what will be the output this message is already there and we are adding toggle message so it will remove this message let’s see the output in console here you can see class main here we have only one class which is main so this toggle removed this message class now instead of this message we will add new so what will happen this new is not available here so it will add this new in this element let’s come back to the web page again and now you can see we have total three class in this element which is main message and new so using this class list. toggle we can add and remove the class from the element if the class name is already there it will remove it and if it is not there it will add the class so this was all about class list property in JavaScript now we will learn about JavaScript events an event is an action that occurs in the web browser when we click on the web page that is a click event when we move cursor over the web page that is mouse move event and when the web page loads that is a load event like that we have multiple type of events in JavaScript let’s create some HTML elements here I will create one div with the ID container and within this container we will create one button with the button tag and button type will be button and here we will add the text click here now we will come back to the web page here you can see this button click here if I click here nothing is happening because we have not added anything so let’s come back you can see we have added the button and clicked on this button but when we click on this button we are actually clicking on the button this div this body and this HTML and this document also so when we click on any element actually we are clicking on the all the patent elements also that means this di with the ID container then body then HTML and this document and in modern browser this click goes up to window object there are two event models that is event bubbling and event capturing so when we click on the button click a start from the button then goes to div then goes to body then goes to HTML and then goes to document so the event flows from the most specific element to the least specific element that is event bubbling but when the event start from the least a specific element it means it starts from the document then event flow to HTML then it flows to body then it flows to div with the ID container then it comes to the Target element which is button so this event model is known as event capturing when the event starts at the least specific element and flows towards the most specific element we may respond to these events by creating event handlers an event handler is a piece of code that will be executed when the event occurs so when we click on this button we will add some code that will be executed after clicking on this button so that code is known as event handler and event handler is also known as event listener so there are three ways to assign event handlers so first one is using HTML attribute for each event there is event handler and their name typically begins with on so let’s see the example we have click event and for this click event we have the event handler on click like this so let’s assign this on click in this HTML element as an attribute so in this HTML element we will add on click so this is the event handler of the click event and within this quote we can write the JavaScript so let’s add a simple JavaScript line console.log so it will log one message in the console of the browser in this one let’s add some text here we cannot add double code because we have already used so I’ll add single quote button clicked so this button clicked message will be printed in the console when we click on this button so let’s see this on the web page this console is Ed right now and if I click on this button that is here in top left corner you can see this message button clicked this event handler attribute can call one function also so let me remove this HTML code we have added event handler which is on click and this on click will call one function so here let’s create one function in a script tag in this script We’ll add one function with the name display MSG that will display message here we will add console.log button clicked let’s add some more text button clicked from FN which means button clicked from function now we will call this function when we click on the button so in this attribute we will call this function write this function here so this is a function call now let’s come back and you can see this console is empty and if I click on this button again you can see the message here it is saying button clicked from FN it means button clicked from function now just come back when the event occurs the web browser passes an event object to the event handler so to understand this one let’s remove this function here and we will add JavaScript code in this attribute so here let’s add console.log and when we click on the button the JavaScript will pass the event object so we can write that event object here event now we can see what is there in this event object let’s see the output so you can see here we have one object now this event object has some properties that we can access so from this event we can find the type event. type let’s see it is displaying the event type event type is Click let’s come back we can add the target so we will get the target element on which the event occurs when we clicked on the button it is displaying the entire button element with all the attributes so it is giving the target element we can also use this keyword inside the event handler and this keyword inside the event handler refers to the Target element let’s see the example example here in this event handler we will try to print this this keyword will refer to the Target element let’s see the output when we click on the button you can see again we got the target element which is button so this keyword inside the event handler refers to the Target element from this keyword we can find the properties of this element so let’s add one ID here I will add the ID is equal to BTN and here we will add this do ID so when we will click on the button it should display the ID value let’s see if I click on the button it is displaying BTN now just come back and instead of this do ID we can simply add ID from the event handler we can directly access the elements property so we are adding console.log ID so it should display this ID value let’s see if I click on the button we got the ID value which is BTN if I write type which is here we will get button it’s here so this was the first method to add the event handler in HTML as HTML attributes now the second method is adding event handler name in the JavaScript so let’s remove this on click from here we have one button let’s remove this type also it will be simple so we we have one button with the ID BTN now we will add the script where we will add the JavaScript So within this script first we have to select this button so let’s add let BTN is equal to document. get element y ID and we will add the ID BTN so we have selected this button element now on this BTN we can add the event handler just add on click and now we can add the code that will be executed when we click on the button so here we’ll create one function and within this function We’ll add console do log and this will print message button clicked after that let’s come back to the web page click on the button and you can see the output in the console button clicked let’s come back you can see here we have the HTML element and in this one we have added the JavaScript in this JavaScript we have added on click event handler name and added one function that will dis play one message here also we can write this keyword that will refer to the Target element and from this we can find the ID this do ID let’s see it is BTN now to remove the event handler we will simply add element which is BTN do onclick and assign null that’s it it when we assign null in this event handler it will remove the event handler so this was the second method to assign the event handler now we will learn the Third Way of assigning event handler so in JavaScript we have two methods with the name add event listener and remove event listener these are two methods that handles the event ad event listener will register an event handler and remove event EV listener will remove an event handler so let’s see the example of add event listener the add event listener accept three arguments the first one will be event and the second one will be one function this function will be executed when the event fires and the third argument is use capture so the third option is optional because by default it is false this use capture is a Boolean value it can be true or false so by default it will be false and we can remove it it is related to the event bubbling and event capturing so let’s ignore that third parameter we will pass to argument event and one function so let’s see one example so let’s try to add this add event list on this button remove it here we will add BTN do add event listener and we will pass first argument which is event so the event will be click we are adding The Click event then a comma here let’s define one function here I’m adding function like this so this is the function defition within this curly Braes we can add the code that will be executed so here let’s add console.log and message button clicked so we have selected the button using get element by ID then on this button we are adding add event listener method that will assign the event handler so in this event listener we are adding first parameter and second parameter first parameter is event so the event is click and the second parameter is a function so we have declared one function here this function will print one message in the console tab when we will click on the button let’s see this output on web page click on this button and you can see the message button clicked as I already said when the event occurs the JavaScript passes the event object to the event handler so in this one we can pass the event object and we can find the type from this event event. type let’s see the output if I click on the button we got event type which is Click now instead of adding this Anonymous function we can add the external named function also so let’s remove it here we can add our second parameter before adding that second parameter let’s create one function with the name display message and this display message will log one message message button clicked now we can refer this display message function here like this after adding this let’s come back and if I click on the button again you can see the message button clicked so we can add the event name and one function it can be a Anonymous function or it can be a named external function we can refer to that external named function with the function name without the parenthesis so this was add event listener method now we will learn the remove event listener method the remove event listener removes an event listener that was added using add event listener so here we have added the event listener using add event listener method now we can remove it using BTN dot remove event listener again we have to pass the same arguments just copy and paste it here so this remove event listener will remove the event listener that was added using this add event listener you can see here I have added the external named function if I add one Anonymous function here then we cannot remove move that event listener using this method so we have to use the external named function when we want to add the event listener and remove the event listener now let’s know about some of the useful JavaScript events so the first one is mouse move event Mouse move event fires repeatedly when you move the mouse cursor around the element and second one is mouse down event when you press the mouse button on the element this event will fire next one is mouse up when you release the mouse button on the element then this event will fire next event is mouse over event when the mouse cursor move from outside to inside the boundaries of the element then Mouse over event occurs next one is mouse out when the mouse cursor is over an element then moves to another element then Mouse out event occurs next one is key down event key down event fires when you press the key on the keyboard and it fires repeatedly while you are holding down the key next one is key up event this key up event files when you release a key on keyboard next one is key press so the key press event occurs with when you press a character keyboard like ABC it files repeatedly while you hold down the key on the keyboard next one is scroll so a scroll event occurs when you scroll a document or an element the scroll event fires we will see more examples of events when we will create the JavaScript projects now we have completed the basic of JavaScript next we will create some JavaScript projects in this video we are going to learn how to create a Notes app using HTML CSS and JavaScript here on my computer screen you can see one button create nodes if I click here it will open one input box and here we can type our text note this is note one so you can add your text note in this white box and if I click on this button again it will again open a new input box where we can add another note and if I click on this delete icon it will delete this note we can delete all the nodes and let’s add the text again two so we have added two notes here this is Note One Note Two And if I close this browser and open the browser again let’s see you can see this note is still displaying here because we have added the local storage that will store the notes in the browser so we will create this note app that will store the text note in the browser using HTML CSS and JavaScript so let’s start this video here I have this folder called Notes app in this one I have one HML file one CSS file and another folder called images in this images folder I have some icons that I will be using on this web page you can find these images download link in the video description let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added margin padding font family and box sizing these CSS properties are applicable for all the HTML elements in this HTML file I have added this title that is the title for the web page then we have added the link tag with the file name style. CSS so it will connect the HTML and CSS file next we have to add the HTML codes in the body tag that will be displayed on our web page so within this body let’s create one div with the class name container now in this container we will add one title in H1 so here we are adding one title notes and after this title there will be one button so let’s add one button and in this button we will add the button text create notes after adding this let’s come back to the folder and open this HTML file with any web browser so you can see this text here notes and create notes button now I will close this browser and I will open it with the visual studio code extension called live server so it will refresh the web page automatically whenever we will add any changes in the code file you can see the same web page but the order has been changed now we have to add some CSS so just come back and copy this class name container and come back to the CSS file within this CSS file let’s add do container and here we have to add the width then we will add minimum um height and in the background we will add the linear gradient color so let’s add the background linear gradient and two color codes then we will add color that will be white and let’s add some space from the top padding top and padding left that will be spaced from the left side after writing this you can see the changes in this web page the text color is white and the background color is linear gradient now let’s come back and uh with this text we have to add one icon also so just in front of this notes we will add one IMG tag so here we will add IMG and SRC and file name images SL the file name is noes. PNG and in this button also we will add one icon so here also let’s add this IMG tag and replace the file path so it is edit.png so we have added two icons with the tag in the nodes and create nodes button you can see this icon and this edit icon in the button now we have to add the CSS for these icons and font size so let’s come back after this container again add container and H1 for the title here we will add display Flex align items Center then font size will be 35 pixel and font weight 600 now within this H1 we have added one icon with the IMG tag so we are adding IMG here and for this image we will set the width it will be 60 pixel so this size for the note icon looks good next we will Design the button so let’s come back and here we will add container then button and in this button we have image so for this image again we will add the width 25 pixel and margin from the right side this will be H pixel let’s copy container and button now we will Design this button using CSS so let’s add display then align items background will be linear gradient two color code button text color will be white and uh font size outline zero and Border zero border radius will be 40 pixel let’s add some padding that will be space inside the button 15 pixel from top and bottom and 25 pixel from left and right side then margin that will be space outside of the button 30 pixel 0 and 20 pixel cursor will be pointer so after adding this you can see this create notes button looks good next we have to add one input box where we can type the text note so let’s come back and uh after this button we will add one tip with a class name nodes container and in this one let’s add one P tag in this P we will add content editable true and we will add one class name also so the class name is input box so it is not visible here because we have not added any text in this P tag so let’s come back and we have we have the input box just copy this one and come to the CSS file write this input box with the dot and here we will add position relative width will be 100% And the maximum width will be 500 pixel then mean height background will be white so we have added width and height in this P then we will add the color padding of 20 pixel margin 20 pixel and zero then let’s add outline none border radius 5 pixel so that the corners will be round after adding this the input box looks good and in this input box we can type anything now we need uh delete icon also so let’s come back and uh before closing of this P tag here we will add a space and before closing of this P tag we will add one IMG tag write the file path images SL delete.png it is delete icon and you can see this icon here next we have to set the size and position for this delete icon let’s come back here we will add this input box then IMG for this image width will be very small 25 pixel Position will be absolute then it will be at bottom 15 pixel space from the bottom and 15 pixel space from the right side cursor will be pointer after adding this you can see perfect position for this delete icon now this input box is displaying by default so we have to to hide this input box and it will be displayed whenever we will click on the create note button and every time you will click on the create noes button it will run a JavaScript and that JavaScript will display the input box so let’s come back and here we have the P you can delete this P tag or command it let me commment this one so it will be disabled and right now you can see we have the text and button we don’t have any input box now we will display the input box with the help of JavaScript so let’s come back and here we’ll click on this icon to create a new file and write the file name script.js so this is our new file script.js next we have to connect this script file with the HTML file so let me come back to the HTML file and just above this closing body tag we will add script SRC and the file name which is script.js now the HTML file and JavaScript file are connected let me open the folder again and here you can see one new file which is a script.js in the same place where we have added HTML and CSS file now let’s come back to the JavaScript and here we will add some variables so let’s add const nodes container con nodes container equal to document. quy selector do nodes container now we will duplicate this line it will be create BTN and here we will add the class name BTN and uh in this button we will add one class name class BTN after that we will add one more variable let nodes equal to document dot query selector all dot input box so here we have added three variables notes container which is for this notes container class name then create button which is for this create button and then we have added another one notes that is for this one input box this input box is not there but we will add it using JavaScript so we will add the multiple P tag with the class name input box so here I’m adding query selected all that will select all the nodes after that let’s add one function then I will explain you each line here we have added create button add event listener it means whenever we will click on the button that is here BTN so it will execute these codes and first it will create one variable called input box and it will store one element document do create element by P so it will create one p element and it will store it as input box then it will create another element with the IMG tag and it will be stored as IMG now in the P element which is input box it will add one class name called input box then in this P element we will add one more thing which is content editable true so we are adding input box set attribute content editable true so it will add one P tag then in the P tag it will add one class name input box then it will add one attribute content editable true and after that we have added img.src we have created one more element IMG and in this Source we will add one file path that is for the delete icon images /d delete.png so it will add this image IMG srz images /d delete.png now we have to display it so we have to display this in the notes container so you can see we have added noes container do appendchild input box it means this input box will be displayed inside this noes container and after that we have added the and child IMG it means this image will be displayed inside this P tag which is input box so after adding this let’s come back to the web page and click on this button you can see it is adding one new input box with the delete icon and we can type anything in this input field it is working now click again it will display the another input field now if I click on this delete button nothing is happening so we have to add one more thing this delete functionality so let’s come back and here we will add this one notes container add event listener again we will add the click event then function if e do Target dot tag name if the target is IMG then e do Target dot so we have added nodes container event listener click so when we will click within this notes container and if the target element is IMG then it will remove that parent element so let’s come back click on this button it will display one input box and here we have the delete button let’s click on this delete icon and it will remove that pent element let’s click again and click on this delete you can see it is deleting the parent element so it will hide that input field this delete is working fine and we can also write something here hello this is new video right now we have added two notes and if I refresh the website you can see it will be disappeared because we have not stored these things in the browser so we have to add the local storage that will store the notes in our browser every time we will open the browser it will be stored and displayed as it is so let’s come back after these variables let’s add some space and here we will add one function update a storage data storage and after that we will add local storage do set item and write the name noes and what we have to store here we will store noes container do inner HTML so whatever is written in the noes container inner HTML that will be stored in the browser with the name notes so whenever we will call this update a storage it will update the data in our browser so let’s copy this one and add it here after deleting it it should be updated so in the next line we will add update a storage next we need one more thing if we write anything in the P then also it should update the data in the browser so here we will add the another condition which is L if here we will add nodes equal to document do query selected all input box now for all the nodes it should update the data in browser so here we will add noes dot for each n sort for the nodes ENT do on key up equal to function and here we will update a storage so it will update the storage when we will start typing edit anything in the P tag next we need one more thing when we close the browser and open the browser it should check the local storage and if there is any data in the local storage then it should display that particular data as a note so let’s come back here at the top after this variables let’s add function so notes notes container do iner HTML equal to local storage dot get item and the item name is notes so if this notes is there in the browser then it will be displayed on our web page just we have to call this function so notes just copy this one paste it here so notes will call this function and it will display this local storage in the container HTML so let’s see how it works if I refresh the web page you can see it is still displaying the note one and Note 2 let’s delete the note one here we have this is Note 2 let’s refresh the website you can see still it is displaying Note 2 so this local storage is working next we will add the one more last thing here will add here we are adding document do add event listener key down event and if the event key is enter Then document. exe command is insert line break and event prevent default it means when we will click entered in our keyboard then it will add one line break in the P tag and it will prevent the default feature of the enter key now let’s see here we will create a new note note one enter line 2 Enter line three refresh the web page you can see it is displaying as it is so finally we have completed this online note app using HTML CSS and JavaScript with the local storage in this video we will create a very useful JavaScript project which is simple quiz app you can create this squiz app or website with the help of HTML CSS and JavaScript let’s see how this squiz app works you can see this question here then we have four options if I select the wrong answer you can see it will become red and the correct answer will become green and now we cannot change our selection now we will click on the next button and if I select the another option let’s select this one and if it is correct then it will be highlighted with the green color and now we cannot click another option we have to click next and here if we will click on this one if it is correct it will become green and let’s click on the next one and now we will select any wrong answer so you can see it is displaying the red color and the correct answer is highlighted with the green color I have added only four questions here if I click on the next button you can see it will display our score you scored two out of four because we have given only two correct answers let’s click on this button play again and if I select the correct answer and again this one this and this one and click on the next you can see it is giving the correct score which is four out of four we will create the squee app using HTML CSS and JavaScript and I will explain you step by step now let’s start this tutorial to create the JavaScript quiz app here in this folder I have one HTML file one CSS file and let me open these files with my code editor which which is Visual Studio code you can use any code editor if you don’t know how to create the HTML and CSS file I will add the video link in the description this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added the margin padding font family and box sizing these CSS properties are applicable for all the HTML element in this HTML file I have added this link tag with the file name style. CSS so it will connect the HTML and CSS file and here we have the the title quiz app easy tutorials next in this body tag we will add one D with the class name app next we will add the CSS so come to the CSS file and here first we will add the dark color on the complete web page so we will add body tag and for this body let’s add one background here we will add one color code and next we will add the CSS for the app so just copy this one add it here in this CSS file with the dot because it is a class name here we will add background so the background will be white after that we will add the width 90% and maximum width will be 600 pixel then we will add the margin 100 pixel from top left right Auto and zero from the bottom then border radius so the Border radius will be 10 pixel so the coordinates will be round by 10 pixel after that we will add the padding of 30 pixel that will be a space inside the box after adding this let’s come back to the folder and open this HTML file with any web browser so you can see this color on the complete web page and here we have the box in the white color I will close this browser and I will open this browser with the visual Studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file so you can see the same web page again but the URL has been changed after that let’s come back and uh within this app we have to add one title so here we will add one title in H1 simple quiz and after that we will add one another div with the class name quiz and within this we will add one question in H2 so let’s add the H2 and here we will add one ID so the ID is question and let’s add any text here so we will add question goes here like this and now you can see this text simple question and question goes here after that we will add some options for the particular question so here we will add one div with the ID answer buttons and within this answer buttons we will add four buttons so let’s create the first one and in this one we will add the class name BTN and here we will add the answers so let’s add the text answer one now we will duplicate this button and we will change the text 2 3 and four and the class name is same after adding this you can see four buttons here after this question answer 1 2 3 4 next we have to design this using CSS so let’s come back and uh here we have the class name quiz so just copy this one and come to the CSS file before the squeeze we have the text in H1 so we will add the CSS for that text so let’s add do app and H1 where we have added the text so for this one we will increase the font size then we will change the color font weight and border bottom then we will add the padding at the bottom now you can see this line here after this text after that we will add that class name quiz and for this quiz we will add the padding it will be 20 pixel and zero after that in this squeeze also we have text which is the question in H2 so here we will add do quiz and H2 so for this question we will add font size so the font size will be 18 pixel then we will change the color and font weight and uh here we have added font weight it will be font size font size 25 pixel now it is good next we will Design these buttons which is answer button so for this button we have added the class name BTN so come to the CSS file here we will add the CSS for BTN so for this button we will add the background so the background will be white after that we will add the color that will be the text color and font weight font weight will be 500 then width will be 100% so it will be full width and border of one pixel solid and this color then we will add the padding that will be a space inside the button and margin 10 pixel from top and bottom and zero from left and right after this padding and margin we will add text align left and uh border radius will be 4 pixel and cursor pointer you can see these buttons looks good next we have to add the hover effect on these buttons so let’s come back here we will add this one and hover we will add the background this will be the background color code and after that we will add the color that will be the text color white and in this one we will add the transition all 0.3 seconds now if I take cursor you can see the background becomes black and the text becomes White next we have to add one more thing which is the next button at the bottom of these answers so let’s come back and uh here after this button and this tib here we will add another button and with this button we will add the ID next BTN and the button text is next after adding this you can see next button at the bottom so we will add the CSS for this next button so let me come back and copy this ID add it here in the CSS file with the has tag because it is an ID here we will add the background then color font weight and width width will be small 150 pixel then we will add the border border will be zero and padding of 10 pixel then margin 20 pixel Auto and zero border radius will be same which is 4 pixel and cursor pointer after adding this you can see this next button here but we have to move it in this Center so here we will add display block and now you can see it is horizontally centered right now this button is displaying so we have to hide this button and this button will be displayed once we will select any option from these answers so let’s come back and here we will add none so the button will be hidden you can see that button is hidden next we have to add the JavaScript to display the correct questions and we can select the answers so let’s come back back and here we will create a new file click on this icon and write the file name script.js this is the script file here we will add our JavaScript next we have to connect this script file with the HML so let’s come back and above this closing body tag here we will add a script tag script SRC equal to script. JS now our HTML file and JavaScript file are connected here we can add our JavaScript so in this Javascript file first we have to set the questions so here we will add const in this Con we will add the name of the variable so it is questions equal to here we have to add the questions so let’s add the first one like this question and write the question text then we have to add the options for this question so here we will add answers here I have added the first answer and correct is equal to false because it is a incorrect answer let’s duplicate it and we will add the other answers here and the second answer is correct so here we will add true so this is the first question and the list of answers now we’ll add the other questions in the same format so here let’s add one comma and we can add this second question here so you can just copy this one and paste here and update the text so I have updated all these questions and answers you can see in front of the correct answers I have added true and other are false here also I have added true and these three answers are false after that we will add another variables in this HTML file I have added this ID question and answer button and next button so we will add the variables for all these three elements so come to the script file here we will add const question element equal to document. get element by ID question which is this one next we will add the variable for this one duplicate this line add this ID here and here we will add the answer button now duplicate this and it will be next button and the ID which is next BTN now whenever we will start the quiz and give the answers the question number and the score will be changing so we will create variables to store the question index and score so here we will add let current question index so the index will start from the zero then we will add let score equal to zero next we will add one function and let me write the code then I will explain you here I have added one function start quiz so when we will start the quiz it should reset the current question index zero and score zero when we will start the quiz here we are adding inner HTML next because at the end we will change the text to the restart or replay so when we will start the quiz again the button should be next and after that we are calling this function so questions so it will set the index zero score0 and set the text next for the next button then only it will call the another function so question that will display the questions now we’ll create this function here in this so function I have added let current question equal to questions. current index so if you will see this list list of questions here we have the first set of question and answer then second then third and fourth so we will get the first question if we’ll add the index zero we will get the second question when we will add the index one so that is written here questions and index number so that will be the current question and we need the question number also so if the index is zero question number will be one if the index is one question number will be two so here I have added + one that will be the question number then in the question element which is this one this is the question element so here we will update the text with the inner HTML so we are adding question element inner HTML equal to question number then one dot and after that the current question and current question dot question so the current question will be this one and here we have the question this one so we will get this text so after adding this we have to display the answer from the current question set so here we will add the code to display the answers so let’s add current question dot answers dot for each here I have added current question do answers so it will come here suppose the current question is this one and it will go here answers and in this answers we have the text and correct so we have to display these text in the buttons so we will add document. create element and the tag name button so it will create one one button tag and we will save it as a variable called button and in this button we have to add one text so to add the text we will add inner HTML and in this inner HTML we will add the answer. text so answer is this one answer. text so it will add the first one then we will add the second one like that so it will add the text in the button then in the button we have to add one class name so we are adding button. class list do add and the class name BTN so it will add this BTN class name in this button after that we have to display this button inside the div which is here answer buttons this div is here so we have to display that button inside this div so we are adding answer button do appen child button so after adding this it will display the question with the question number and it will display the answer now we have to call this a start quiz function to display the output so let’s copy this one and add it here at the bottom start quiz so it will call this a start quiz function and it will set the current index z a score 0 and button text next then it will call the so questions and this so questions will display the question with the question number and uh it will display the answers in the button so after adding this let’s come back to the website and here you can see it is displaying the question with the question number one then we have the previous text that we have added in the HTML file which is Answer 1 2 3 4 then we have our answers that we have added with the variable here you can see the answers for the first question Sark blue whale elephant and jff so you can see these answers here but we have not added click function here right right now so now let’s come back and we have to hide these things to hide these things we have to reset the previous questions and answers so let’s come back and uh here we will add one function before displaying the question here we will add one function reset a state that will reset the previous question and answer now we have to Define this function so let’s add it here function reset state in this reset State let’s add the next button dot style do display it will be none then we will add while answer button it will will be buttons s and here also we will add buttons in this one so answer buttons DOT first child so suppose it has a child element then we have to remove that here we will add answer buttons dot remove child answer buttons DOT first child so it will remove all the previous answers and here also we have added answer button it will answer buttons yes answer buttons do app and child so after adding this let’s come back and here you can see the first question with the question number and list of options and if I click here nothing is happening next we have to add the click function on these answers so let’s come back here we will add button dot add event listener click and here we have to add one function name so when we will click on the answer button it will call this function select answer and before this click event we will add if answer dot correct so if it has some value then it will add button dot data set dot correct equal to answer dot correct so it will add the true or false in this data set correct from here this false true it will add in this button data set now we will add the function which is Select answer so let’s define this function above this a start quiz so here we will add function so when we will click on that uh button it will add the selected button element in this variable selected vtn and then it will check the selected vtn and data set true so if the data set is true then it will add the class name correct and if it is not true then it will add the class name incorrect now for these class name we have to add the background color so we will change the background color for the correct and incorrect class name so let’s come back to the CSS file here we will add correct and background in this background we will add one color code now we will add the background for the incorrect class name Incorrect and this background color after adding this let me come back to the website and if I click on the first one you can see the background becomes red because it is incorrect if I click on the second one you can see it becomes red because it is correct and if I click on the third one you can see it is red and the fourth one is red now we can click on any number of times so we have to disable the click after selecting one answer and when we will select the wrong answer it should automatically highlight the correct answer with the green color so to add that one let’s come back here in the subscript after that we will add so here we have added aray from answer buttons children for each so for each button it will check the data set if it is true then it will add the class name correct suppose we have selected the wrong answer then it will go and check the other answers and if it is true then it it will add the green color with this class name correct and after that it will disable the button so we cannot click on the any button and after that it will display the next button so here we are adding next button style. display block so it will again display the next button so that we can go to the next question so after adding this let’s come back to the website and if I click on the first one which is the wrong answer you can see the second one becomes green because the second answer is correct and it is displaying the next button and now we cannot click on the any other button let’s refresh the website and if I click on the correct answer it is displaying the green color here and now we cannot select any other next we have to hide the hover effect when we select the button so let’s come back and uh in this CSS file here we have added BTN hover so in this one we will add one more thing h and uh not disabled so the hover effect will work when the button is not disabled and when the button is disabled the hover effect will not work and we will add one more thing here we will add BTN disabled and uh cursor no drop after adding this let’s come back and refresh the website if I click here you can see we will not get the hover effect now and the cursor becomes red we cannot click on any button we can just click on the next button we have to add one more thing when we will select the correct answer the score should be increased so let’s come back and here we have added the class name correct in this one so here only we will add one more thing score Plus+ so it will increase the score by one next we will add the function for the next button so here we will add next button do add event listener and the event is click here we will add add a function and in this one we will add if it will check the current index if the current index is less than the length of the question it means the number of question is four then the question length is four so if the index is less than that then here we will add one function handle next button or else it will add a start quiz suppose if there is no question and we will click on that button so it will restart the quiz and here we have to Define this function handle next button so above this one here we will add function handle next button and in this one we will add current question index Plus+ it will increase the question index y1 when we will click on the next button and again we will add if current question index less than question length then so question function with the updated question index else it will display the score so score so if there is another question it will display the another question and if it is not there then it will display the score when we’ll click on the next button next we have to Define this function so cord so here let’s add function sour score and in this one let’s add reset state that we have already created to display the score we have to call this reset function and instead of question we have to display the score so we are displaying the question in the question element so in this one we will add inner HTML and let’s add the text in backtick here we will add us code so it will display the escore out of the length of question and after that we will add next button dot inard HTML equal to play again and uh next button will be block so let’s add next button do style do display block after adding this let’s come back to the website again and let’s select the correct answer next again correct answer next again we will click here next and here next you can see us code four out of four and we are getting the button play play again it will restart the quiz let’s click the wrong answer it will display the correct one let’s click next and wrong answer so we have selected two wrong answers let’s click again click here it is also wrong and if we click here on the correct one so you can see the score one out of four because we have selected only one correct answer out of four and we are getting play again so finally this quiz app is working you can update your question in this JavaScript and you can create your own quiz app or quiz website using HTML CSS and JavaScript in this video we are going to learn how to add the validation in contact form using JavaScript so here you can see I have created a contact form where you can see the input field for the name phone number email ID and message and at the end we have the submit button if I click on the submit button you can see it is giving an error name is required and there was one more error message at the bottom called please fix error to submit first we have to fix the error which is in the name field so here we have to enter the name because right now the name field is empty so let’s add anything here if I write like this still we are getting an error write full name because we have to add the first and last name so let’s add a space and write full name like this now you can see a green check icon that means this input field is correct so after adding the correct data in this name input field let’s click on the submit button again so it is giving error in the phone number field and here it is saying phone number is required so let’s add some characters here if I write like this it is saying phone number should be 10 digits so let’s add any 10 digit number here so so now you can see check mark it means this input field is correct after that if I click on the submit button again it is giving an error in email field so here also we have to add the email ID so let’s add the email ID like this so right now this is not the correct format so that’s why it is saying email invalid so we have to add the email in proper email format so if I write like this now you can see a check mark let’s click on the submit button again and it is giving an error 30 more characters required because we have added the limit minimum 30 colors should be there in the message box so here let’s add any message you can see as I’m writing the text here it is decreasing the required character right now it is saying 16 more characters required after writing minimum 30 characters in this message field we will get this check mark now we can submit this form so let’s click here and you can see it will submit the form so without collecting all the fields this form will not be submitted and once we will collect all the input fields and click on submit button this form will work so we will learn how to add this validation in form using JavaScript now let’s start this tutorial to add validation on contact form using JavaScript I have already already created multiple tutorials about creating a contact form using HTML and CSS that’s why in this video I’m not going to design this form you can go to the video description and download this HTML and CSS form and in this video we will only talk about the validation so let’s come back to the folder and here you can see I have this HTML and CSS file that you can also download from the video description once you will open these files with the code editor you will see this HTML file where I have added the container and then we have the form tag and in this form we have added this icon and here we have added the font awesome link that’s why we have added this font awesome icon then we have the input group and in this one we have the input field for the name this is for the phone number this is for the email and this one is for the text box and after that we have the button and you will get this CSS file also where we have added all the CSS for the design of the form once you will open this HTML file with B browser you will get this form like this next we will display the error message on this form so let’s come back to the code and here you can see we have added the input field for the name so just below this input field we will add one span tag and in this span let’s add one ID also so I will add the ID name error and in this name error let’s add a error name is required like this simply we will add the span tag in all the input group just below the input field so here also we will add this fan tag and this is for the phone number so we will add the ID phone error and here also one message phone is required let’s copy this one and add it just after this input field for the email here we will add the ID email error and we will add the message email is required and uh after that we will add one span here this is for the message error message is required like this and uh we will add one message after this submit button also so here also we will add a span and we will add the ID submit error and one message please fix error so we have added these error message in this HTML file and let’s refresh our website and now you can see these message here at the end of all the input fields and one error message at the bottom left corner of this form so we have to change the position and color for these error message for that we will come back to the HTML file and here you can see we have the class name called input group and in this input group we have the span tag where we have added the error message so let’s add this class name in the CSS file and here we will add the span and for this aspan we have to set the position Position will be absolute then we will add the bottom bottom will be 12 pixel and right 17 pixel we will add the font size it will be 14 pixel and color so the color will be red because it’s an error so you can see the position has been changed for these error message we have to add the Cs for this one also which is for the submit error let’s come back and here you can see we have added the ID called submit error so let’s copy this ID write it here with the hashtag because it is an ID and here we will add color red that’s it so this message is also in the red color so we have added the position and color for the error message but right now this message is displaying by default but we have to display this message after validation using JavaScript so we will remove these error messages for now and it will be displayed later let’s come back and come to the HTML file and just remove this message span tag will be there we have to remove the message only let’s remove all the error message like this it’s done again you can see the simple contact form now we have to add the JavaScript file so here we will create a new file go to files new file and uh save this file as uh script.js make sure the file name should be JS so we have created a new file and uh next we have to come to the HTML file and just at the bottom before this closing body tag we will add a script a script open and closing tag write SRC and write the file name that we have just created which is script.js so it will connect the Javascript file with the HTML file next we have to add the variable for all these ID that we have written here in this HTML file so let’s come to the script file this is the script.js and here we will create variable so let’s add where name error equal to document dot get element by ID and in this ID we will add the ID that we have added in the HTML file so you can see we have added the ID called name error just copy this one and place it here so this is the first variable just duplicate this one and change the name it will be phone error this is for the email error this is message error and this one for the submit error and here also we will change the ID so we have added these variables next we have to add the function that will validate the input box so let’s come back to the stml file and here we have the input field for the name in this one we will add one ID so let’s add one ID called contact name and we will add one event so it is on key up on key up equal to and here we will add one function name so let’s add any function name validate name like this so here we have added one ID and one function next we have to Define this function that we have added here so just copy this function and come to the script file here we will add function write the function name like this so this function will be executed whenever we will start typing anything in the input field so here we will add one variable and write name equal to document Dot get element by ID and in this ID we will add the ID that we have just created which is contact name copy this one add it here at the end we will add dot value so this variable called name Will store the content written in the input box which is for the name so it will take the value of the input field and now we will add the condition so here we will add if name Dot this will check whether this name length is zero it means the input field is empty so it will display an error called name is required and where this error message will be displayed it will be displayed in the variable called name error and this name error is for the ID called name error that we have added here in this span tag so in this span tag we will see this message called name is required when the length is zero it means the input box is empty next we will add the another condition here we are adding this condition so this expression is exactly checking the first character should be alphabet and after that there will be one space and after that it could be any character A to Z here we are adding exclamation it means value is not matching with this expression then it will give an error so what will be the error just copy this one paste it here and here we will add write full name like this and one more thing once it will give an error it will return false like this and we will add this return false in this if condition also so whenever there will be an error it will return false in this condition also if it will give an error it will return false if there is no error then what will happen it will display a success message so let’s add name error dot inner HTML equal to and in this one let’s add valid like this Suppose there is no no error then it will say valid and then it will return true like this it is not and it will be a dollar sign like this so again refresh the website and you can see if I write a first name and write anything in the second name it will say valid you you can see the message has been changed to valid so instead of valid we want to display a check sign so you can see in the HTML file we have added this font awesome link so we can add the font awesome icons so let’s come to the font awesome website here we will search for one icon so let’s go to the icon and search for check we’ll click on this one check Circle copy this and come back to the script file and in this script instead of this valid we will add this HTML code like this and we will change the color also so it is in the it tag you can see it is in the it tag so we have to use this it tag in the CSS file just come to the CSS and copy this input group span and uh in this Supan we have the it tag for the icon and here we will add the color so let’s add the color of this one after adding this color come to the web page and here we will add one name now you can see a green color of check sign so it is working fine next we will add the validation for the phone number field so let’s come back again come to the HTML file and as you can see we have added the ID in the name field and one function so same thing we will do in the phone number field so just copy it here so this is for the phone number field so it will be contact phone ID is contact phone and here we will add validate phone like this come to the script file and let’s copy this one paste it here instead of validate name we will add validate phone this is for the phone number validation and again we have to add the variable so let me just copy this one only paste it here it will be phone equal to document. G by ID contact phone ID is contact phone so this phone will store the value written in the phone number input field next we have to add the condition to check the phone number so here let me write the condition then I will explain to you so you can see here we have added phone. length equal to Z so it will check whether the phone number field is empty then it will display and eror phone number is required next it will check the length of the phone number if it is not equal to 10 then it will display an error phone number should be 10 digits in this condition it is checking the phone num should be 0 to9 and for 10 characters and if it is not like that then it will display an error called only digits and if there is no error like this then it will display a check icon and it will return true so after adding this let’s check the phone number field come back to the web page and here if I write you can see phone number should be 10 digits so let’s add more digits and now you can see a check icon you can see if I add any character like this Zed y anything it is saying only digits please so we need to add digits and if we add 10 digits it is fine so this phone number validation is also working now let’s come back and we will add the validation in this email field so let me just copy this one and paste it here in this email input field write the ID contact email and this is validate email next we will add the script so let’s copy this one it will be validate email then copy this paste it here it will be email document. get elment by ID contact email so it will store the value written in the email input field and now we will check the conditions for so in this validate email function we are adding this variable that will get the value of the input box and then it will check the length if it is zero it means it is empty so it will display an error email is required and return false next if there is some value then it will check this condition and here it is saying it should be any alphabet it may contain a DOT or underscore or the siphon and it can also contain any number and after that there should be one at theate after at theate there will be some alphabets and then one dot and after that dot there will be another alphabet it could be 2 three or four characters so if the email format is not matching with this one then it will display an error called email invalid and return false and if there is no such error then it will display the check icon and return true here we will remove this and save this file let’s refresh the website again and if I write uh correct email here now you can see it is displaying a check icon it means the email ID is valid next we have to add the validation for the message box let’s come back and here we will add one ID and one function copy and paste it here write the ID called Contact message and this is validate message now let’s come back to the script file and copy this one here we will add validate message and in this one again we will add one variable so it will store the value written in the message box and after that we will add one variable where we will add any number required equal to so if we want 30 characters then we will add 30 characters is required and here let’s add another variable and it is left left equal to required minus message do length so it will give the value how much characters is left and now we will add the condition if left greater than zero it will be giving an error message message error dot inard HTML and then it will return false and if there is no such error and the character is more than 30 then it will display a check sign just copy this one paste it here and here we will add message error. innerhtml that’s it here it will be this one message refresh the website and now you can see if I write something 29 more characters required if I delete this one it will display 30 more characters required and if we write some text here and now you can see the error message has gone and we will get the check icon so this message box validation is also working fine next we have to add the validation when we will click the submit button so let’s come back in this button we will add onclick and here let’s add return space and one function validate form next we have to Define this function called validate form in the JavaScript so let’s copy this one come back to the Javascript file and here we will add a function validate form and in this one first it will check all the functions that we have added in the different input field so here we will add if exclamation validate name then we will add exclamation validate phone in the series wise we are adding so this condition we check if any of these are false then it will display an error message so here we will add submit error dot inner HTML and one message like this and after that it will also return false after adding this again refresh the website and simply click on the submit button and you can see here it is displaying please fix error to submit so M submit but right now this error message will be displayed continuously so we have to hide this message after a few seconds so let’s come back and here we will add submit error dot style do display it will be block so it will be visible and here we will add set timeout display none so after 3 second it it will hide the error message which is please fix error to submit so this message will be displayed for 3 second and after 3 second it will be hidden because we are adding display none in the set timeout and it will return false so it will not submit the form so let’s check this one and if I click here you can see this message will be hidden after some time you can see this message is hidden so this complete form is working fine right now let me check check all these input field and if I write a name here then we will add one phone number and any email ID and message after collecting all the input field if I click on sub MIT it will submit the form successfully without any error message so it is working fine so we have completed this form validation using JavaScript in this video we are going to learn how to create an image gallery that will slide horizontally using Mouse wheel usually when we rotate the mouse wheel the web page scroll down or a scroll up but if I take cursor over this image gallery and rotate the mouse wheel it will scroll the gallery horizontally either in the left side or right side in this image gallery we have added two control icons also that is for the backward and forward we can click on these icons to scroll the gallery to the left side or right side we have added one more effect if I take cursor over this image you can see the image becomes colorful all the images are gray right now when we take cursor it becomes colorful and you can see the image size is also increasing when we take cursor so we will create this horizontal scroll with mouse wheel using HTML CSS and very simple JavaScript this will be very good JavaScript mini project for your resume now let’s start the video here I have this folder and in this folder I have one HTML file one CSS file and another folder called images and here you can see some images and two icons you can find all these images download link in the video description now I will open these files with my code editor which is Visual Studio code so this is the HTML file where I have added the basic HTML structure and this one is the CSS file in this HTML file I have added this title then this link tag that will connect the CSS file now we will add the code within this body tag so here we will create one div with the class name gallery and within this Gallery we will create another div and in this div we will add span and inside this span we will add the first image with the IMG tag here we will add the file path of the image it is images / image1.png Let’s duplicate this line and we will add the another image image 2 and three after that let me open this web page with browser so you can see three images on this web page now let’s come back and here we will copy this class name and come back to the CSS file here first we will add the Cs for the body and here in this body we will add the background after that add that class name Gallery here we will add the width it will be 900 pixel and display Flex after that we will add gallery and div for this div let’s add the width of 100% display grid and grid template column Auto auto auto so we will get three image in one row after that we will add grid gap of 20 pixel and padding of 10 pixel then we have the IMG tag so here we will add gallery div and IMG width will be 100% for the image now you can see perfect size for these images next we will add three more images so let’s come back and duplicate this div and replace the image file name it is 456 so we have total six images you can see the images size becomes small so let’s come back and here we will add Flex none now you can see it is perfect size for the image and you can see the horizontal scrolling here the complete website is scrolling so let’s come back and uh here in this Gallery we have to add overflow X scroll now only this Gallery will scroll the gallery width is 900 pixel and it is scrolling inside that div next we have to hide this horizontal scroll bar so let’s come back and here we will add gallery and webkit scroll bar display none so that horizontal scroll bar is hidden but we cannot scroll it with the mouse wheel so let’s come back and uh Above This Gallery we will add another div with the class name Gallery WAP and in this one we will add one image and file name back do PNG then another file name next. PNG here we will add ID back BTN and next vtn and let’s remove it and add it here within these images so first we have the back arrow then all images and again next Arrow you can see the back arrow at the top and the next Arrow at the bottom here we will add gallery W display Flex align item Center and justify content Center then we will add the margin of 10% Auto you can see it is horizontally centered now just come back and copy this ID back vtn then next vdn we are adding hashtag because it’s an ID here we will add the width 50 pixel cursor pointer and margin 40 pixel now the size for the icons are perfect next we will add the hover effect on these images so let’s come back and here we will add gallery div IMG and hover and uh let’s add filter gray SK zero the G scale will be zero and come here and we will add cursor pointer and transform scale 1.1 so it will increase the size just copy this filter gray scale and add it here and let’s add 100% so the default gray scale will be 100% so the image will be gray let’s add the transition transform 0.5 seconds so it will take5 seconds to increase the size you can see the size is increasing and the image becomes colorful when we take cursor so we have added the hover effect after that we have to enable the horizontal scroll using Mouse wheel so just come back and here above this closing body tag we will add a script tag in this script tag we will add the JavaScript so here we will add let scroll container equal to document dot query select and we will select this one do Gallery so we are selecting this class name after that we will add let back vtn equal to document. get element by ID because we have the ID here back vtn so write it here now duplicate this line and it will be next vtn so we have selected the gallery div then next vtn and back vtn after that let’s call copy this one add it here here we will add add event listener and it will be wheel so it is wheel event then we will add this Arrow function and when we will rotate the wheel this function will be executed so here we will add EVT do prevent default it will prevent the default feature that scroll the web page down or up next we will add the scroll container scroll left plus equal to EVT dot Delta y after that come back to the website and if I take cursor over this image and rotate the mouse wheel this slider is scrolling we can scroll in the left direction or right direction you can see this image gallery is scrolling horizontally with the mouse field now we will add the click feature on this back arrow and next Arrow so let’s come back and hit we will add next BTN do event listener click because we will add the click function here also we will add the arrow function and this function will be executed when we will click on the icon here we will add scroll container do scroll left plus equal to 900 because the width is 900 for the gallery again duplicate it and here we will add back BTN and it will be minus equal to 900 that’s it after that let’s come back and if I click on the back button it is a scrolling the gallery to the left side and if I click on the right button it is a scrolling the gallery to the right side but when we click on these icons it immediately scroll it by 900 that’s why we cannot see the scroll animation so let’s come back and here we will add scroll container dot Style dot scroll behavior and we will add the scroll Behavior smooth let’s copy it and paste it here same thing now just come back and if I click here you can see it will scroll smoothly you can see this Gallery is scrolling horizontally when we click on these next or previous button and we can scroll it using the mouse wheel also but you can see this mouse wheel scroll is not smooth right now so let’s come back and uh here copy and paste it in this V event and here we will add Auto that’s it after adding this let’s come back now if we rotate the mouse wheel this Gallery is scrolling smoothly and when we click on the icon here also it is scrolling smoothly and we have the hover effect also so finally we have completed this beautiful image gallery that scroll horizontally using the mouse wheel in this video we will learn to make a digital clock using JavaScript let’s check the current time in my laptop at the bottom right corner so the time is exactly same as the time displaying on my website we will Design This digital clock using HTML and CSS then we will update the local time using JavaScript this is very useful JavaScript project for your job portfolio so let’s start to make this digital clock using JavaScript a step by step here I have this folder and in this folder I have added one index.html file one style. CSS file let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added the basic HTML structure and this one is the CSS file where I have added the margin padding font family and box sizing these CSS properties are applicable for all the HTML elements in this HTML file I have added this title digital clock using JavaScript e tutorials and then I have added this link tag that will connect the HTML and CSS file because here I have added hdf style.css now we will add the code within the body tag so so here let’s create one div with the class name hero and now we will add the CSS for this class name write this class name here in this CSS file and here we will add the width height main height will be 100 VH then we will add the background and in this background we will add the linear gradient color here we will add one angle and two color code then we will add the color this will be the white color and let’s add the position relative after adding this let me come back to the folder and open this HTML file with any web browser so you can see this gradient color on the complete web page let me close this browser and I will open it with the visual studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file and save the code file so you can see the same web page again with the gradient color now let’s come back and within this div with the class name hero here we will create another di with the class name container inside this container we will create another with the class name clock and in this clock let’s add the time like this save this and open the web page you can see this time here at the top left corner 0 so let’s add some CSS let’s come back and here we have the class name container just add it here in this CSS file and here we will add the CSS for this content container we will add the width it will be 800 pixel and then we will add the height height will be 180 pixel after that we will add the position absolute top 50% left 50% and transform translate – 50% and – 50% so that this element will be in the center of the web page for now here we will add one background so let’s add the background red and open the web page so you can see this red color of box in the center of the web page now we’ll remove this color let’s come back to the HTML file and here we have the class name clock so let’s add the CSS for this clock here we will add the width and height 100% after that we will add the background and in the background we will add some color with less opacity so we will add rgba so this is the color code for the background then we will add the Border radius of 10 pixel and uh let’s add display Flex align items Center and justify content Center so that the text inside this clock will be in the center and after that come back to the web page you can see this color in this box now we will add two other elements that is a square and circle so let’s come back we will add the element with the help of cudio elements so here in this container we will add two cudio elements which which is before and after so add this container then write double column before and in this before we will add content content will be empty then let’s add the width and height width will be 180 pixel and height also same 180 pixel then we will add the background here we will add one color code then border radius will be 5 pixel very small and Position will be absolute left Min – 50 pixel and top also Min – 50 pixel then right Z index minus one after adding this you can see one element at the top left side of this horizontal box now we will create another element that that will be one Circle so let’s come back and duplicate this one here we will add after this is same content width height and we will change the background color and here we will add border radius of 50% so that it will be a circle Position will be absolute and here it will be on right side so right minus 30 pixel and it will be at the bottom so write bottom minus 50 pixel that’s it now you can see one Circle in the right side next we have to make this horizontal box blur so let’s come back and here we have the clock so in this clock we will add backdrop filter blood it will be 40 pixel after that you can see the web page it looks good next we have to change the size for this text and we will add the name also like minutes second hours so let’s come back and uh here let’s remove this one instead of writing the text directly we will add one span tag and in this span first we will add 0 0 Let’s duplicate it here we will add the column after updating this you can see again it is same we have just added the span tag for each number let’s come back here we have the span inside this clock so come to the CSS file let’s add dot clock and a span so for each a span we will increase the font size so let’s add the font size 80 pixel we will add the width 11 10 pixel and uh display will be inline block and text align Center and P relative after that you can see some space between these numbers and the font size is also increased next we will add the name like hours minutes and seconds so let’s come back to the code again and let’s copy this clock span and write the sudo element after and this after let’s add the content in this content it will be empty font size 16 pixel position absolute bottom – 5 pixel and left 50% transform translate x – 50% in this content we can add the text so let’s add ours it will be 16 pixel PX and after applying this you can see we have the text here hours hours hours like this and we have to remove this hours and it will be different in the first one we will add hours then minutes and seconds to change this one we will come back to the the HTML file and in this HTML file let’s add some IDs in the first span we will add the ID HRS for the RS then in the second number here we will add ID Min n that is for minutes and in the last one we will add the ID SEC for the seconds and let’s come back to the CSS file and remove this content from here remove this and here at the end we will add that ID like HRS and here we will add sudo element after write content ours duplicate this line it will be minute and second and here also minutes and seconds after adding this let’s come back to the website so you can see in the first number we are getting hours then in the second one minutes and last one seconds next we have to update the time and uh to add the current time we need to add the JavaScript so let’s come back to the HTML file and here at the bottom just above this closing body tag we will add a script open and closing tag and within this script we will add all our JavaScript code so here we will add let HRS equal to document. getet element by ID and the ID is HRS that is from here let’s duplicate it it will be minute and second to get the date and time we need to use the JavaScript object called date so here let’s add let current time equal to new date and if we print this current time let’s add console.log current time you will see the local time and date let’s come back to the website and open the console here you can see it is displaying Tuesday May 30 2013 and this is the time so it is our local time now we have to get the time only we have to remove the date and day so let’s come back here you can use the JavaScript methods get hours get minutes and get seconds to get the hours minutes and seconds from this time so let me show you here we will add current time dot get ours and open the web page you can see it is displaying the hours 15 if we come back and add get minutes it will display the minutes in current time 37 and like that we can get the seconds also so let’s display all those things here we will add HRS do inner HTML equal to current time dot get hours so it will display the hours of current time duplicate this it will be minutes Min and it will be seconds second and here also we will update the methods get minutes and another method called get seconds so after updating this let’s come back to the website you can see the current time here which is 15 38 and 39 let me show you my laptop current time it is same 1538 but you can see this time is not updating so we have to update it it at every second for that we will use the set interval so let’s come back and we will add all those things in a set interval here we will add comma 1000 milliseconds that means 1 second and and within this we will add all these code so it will execute this code at every 1 second now just come back to the website again and you can see this seconds is increasing and this minute is also increasing right now it is displaying only one digit so suppose you have the numbers less than 10 we can add one zero in front of that number for that let’s come back to the JavaScript again and here we will add one if condition so we will add the inline if condition copy this and here we will add plus this one and here we will add the condition if less than 10 if it is less than 10 then it will add one zero or if it is not less than 10 then it will be empty like this so we have to add the same thing in the other one here and here and update the methods it will be minutes minutes and seconds after updating this let’s come back to the website again and finally you can see it will display the double digit in the numbers now you will see it is starting from 0 1 02 03 like that so finally we have completed our digital clock using HTML CSS and jav JavaScript in this video we will create a product page design that you can use on e-commerce website here I have added a product image on the left side and product details on the right side in this product image we have some control buttons when I click here you can see the product image is changing in the product detail section you can see the product name price and offer after after that we have some select option for variable products we can select the size and color of the product then we have input field to select the product quantity and at the bottom you can see by now button we will create this product page design using HTML CSS and JavaScript here in this folder I have created one index.html file one style. CSS file and you can see another folder with some images you can find all the images download link in the video description let me open these files with my code editor which is Visual Studio code you can use any code editor so this is the HTML file where I have added basic HTML structures and this one is the CSS file and I have connected this CSS file with this link tag in the HTML file now we will add code in the body tag so here we will create one dip with the class name container in this container we will create another div and let’s add the class name product in this product we have to create two columns so first we will create the left TI with the class name Gallery where we will add the product image gallery and let’s add another div with the class name details where we will add the product details like product title description and buttons next we will add the image in the first div which is image gallery so here we will add one IMG tag write the file path of the image so this is the images / image 1.png after adding this let’s come back to the folder and open our HTML file with any web browser so you can see this image on the web page let me close this browser and I will open this browser with the visual studio code extension called live server so that it will refresh the web page automatically whenever we will add any changes in the code file and save the code file so you can see the same B page page again now let’s come back and we will add the CSS so let’s copy this container write it here in the CSS file here we will add some CSS properties like width then we will add Min height then we will add the background in this background we will add one color code let’s add the display Flex align items Center justify content Center so that the product will be in the center of the web page let’s copy this class name product write it here so for this product we will add the width it will be 90% and maximum width will be 750 pixel then we will add display Flex so left and right column will be side by side now we will add the CSS for this gallery and details so let’s add this Gallery here so for this Gallery we will add Flex basis 47% it means width is 47% after that we will add the background so this is the color code now in this Gallery we have one image so again write this one then write IMG tag so for this image we will add the width it will be 100% and display it will be block let’s add some padding from the top 100 pixel and after adding this again refresh the website you can see this image on the web page next we will add the CSS for the right column which is details so here we have details just copy this one write it here in this CSS file so for this one we will add the flex bases 53% it is width 53% so now we will add the background it is white and we will add some padding it is 40 pixel and let’s add the padding from left side it will be 60 pixel now you can see this white color in the right side and in the left side you can see this image now we have to increase the size for the left one so here in this Gallery we will add transform scale 1.08 so it will increase the size let’s add the Box Shadow also so here we will add box Shadow next we will add the same box shadow in the second column which is details so just copy this one and paste it here after adding this let’s come back to the website again you can see the size for the left column is increased and you can see the shadow also now we will add some details in the second column so here in this second div we will add space and here we will add one title in H1 it will be the name of the product casual t-shirt next we will add another text in H2 so it will be the price of the product again we will add H3 and here let’s add the discount 30% off after that we will add some description in P tag so this is the description after adding this you can see this title and description on the web page so we have to design these things so just copy this class name details WR it here and here in this details we have the first title in H1 so for this H1 we will add this color code and we will add the font size you can see different size for this text again write this class name then write H2 for the second Title Here we will add another color and font size it will be 30 pixel and we will also change the font weight 600 let’s add this class name again and here we will add H3 for the discount so in this one we will add color and margin from the bottom to add some space at the bottom so you can see these titles looks good next we will add the CSS for this description for that we will come back back and here in this details here only we will add font size it will be 13 pixel and we will change the font weight let’s add the color after adding this this description is also looking good next we have to add some radio buttons where we can select the size and color so let’s come back and after this P we will add one form tag and in this form we will add one div so let’s add the div with the size select and in this size select first we have to add one text in P tag it is size then we will add one label in this label we have to add the four it will be small and inside this label we will add one input field so in this input field input type will be radio so it will be a radio button then we will add the name let’s add size and in this ID we will add the same thing which is here for this ID and for should be shame after that we will add a span and in this span we will add s s means small let’s duplicate this label and change the ID and for so this will be medium and here also medium this will be M duplicate again and write large and ID also large and a span L again we will add this one then right extra large for Excel let’s duplicate again and this is the last option dou x large double XL after adding this again refresh the website you can see this text size then we have the radio buttons for SML Xcel and double XEL you can select these radio buttons now let’s come back to design this one we will copy this form here we will add details form so for this form we will add the font size it will be 15 pixel then we will add the font weight then we have the size select so let’s copy this one write it here size select in this one we will add display Flex so that the text and radio buttons will be in the same horizontal line aligned items will be Center and some margin from the top to add some space again copy this one here we will add P so for this P tag we will add the width it will be 70 pixel now you can see this size here then we have some space and after that these radio buttons and text next we have to change the color of these text which is SM L XL so let’s come back and copy this one here we will add input then checked so if the input is checked we have to change the color of the span text so here we will add plus span and color we will add this blue color and we will also increase the font weight it is 600 so you can see when I select any radio button the color for the label text is changing and the font weight is also changing next we have to hide these radio buttons there will be only text copy this size select input and just add display none so it will be hidden you can see we have only text here and we can click over these text to select any radio button that is invisible so again come back here we will add site select then a span so for this span we have to add some space so first we will add some padding then margin from the right side and we will add the cursor pointer so it looks good and we can click on any text to select this one and the color and font weight is changing when we select any size so we have completed this size select let’s come back and after closing of this div which is for the size select or you can add it here just above this closing form tag here we will add one div with the class name color select where we will add radio buttons to select the color so in this one again we will add text in P tag it is color then we will add label for let’s add red color and in this for again we will add input input type will be radio then we will add name in this name we will add color and let’s add the ID red for and this ID should be same after that again we have to add one span and in this span we will add one class name so it is color one after adding this let’s duplicate this complete label total we have four colors so let’s change the color it is green and here also green and in this span we will add the class name color two now for the third one we will add blue and ID also blue this is color three now for the fourth we will add for pink ID pink and class name color four after adding this let’s refresh the website again you can see this color and then we have four radio buttons now we have to align all these in same horizontal line so again come back let’s copy this class name color select write it here in the CSS file and for this color select we will add display Flex then align items Center and some space from the top again WR this class name and in this one we have P tag so we will add width 75 pixel you can see it is in the same horizontal line we have some space after this color next we have to add different color with the each radio buttons so let’s come back and in this CSS file we will add this class name again then write span so for this span let’s add display it will be inline block then we will add width and height it will be 15 pixel after that we will add border radius it will be 50% so that it will be a circle after that we will add some spad so we will add margin right 15 pixel and cursor will be pointer now we have to add different color in each as span so we have added class name color 1 2 3 4 so for all these span we will add different color so here we will add color one and write background it will be R let’s duplicate it and we will change the class name color 2 3 4 and for all these class name we will add different color now we have added different background in all the span again refresh the website and here you can see we have different color circle with the each radio buttons next we will hide these radio buttons only color will be visual so let’s come back and copy this class name color select then input here we will add display none that’s it so it will be hidden you can see we have colors here now we have to select the color so let’s come back and here we will add color select input checked so whenever the input button is checked we will Design the span so here we will add plus a span transform scale 0.7 so it will reduce this size size then we will add box shadow in this Shadow we will add two Shadow this will be in the white color and again we will add the same thing let’s add a comma and write another Shadow so here we will add black color and it will be 6 pixel so after adding this again refresh the website and you can see see when we click on any color there is one circle around it so this select option is working next we will come back to the HTML file and here before this closing form tag here we will create another div with the class name quantity select inside this div we will add one title in ptag it is quantity and again we will add one input field and input type will be number and value it will be one after adding this let’s refresh the website you can see this quantity and this input field with the value one and we can increase and decrease this value with these Arrow let’s come back and copy this class name quantity select write it here in the CSS file here again we will add display Flex align items Center and some space so margin top 20 pixel WR this class name again then write p and for this P we will add width it will be 75 pixel you can see it is in the same horizontal line next we will Design This input field let’s come back and here we will add quantity select input so for this input field we will add the background this is the color code for the background then we will add border it will be zero and outline it will be zero let’s add some padding inside this input field then we will add width it will be 50 pixel and B radius it will be 12 pixel you can see this input field looks good we can increase and decrease the value by clicking on this up and down buttons after adding these input fields we will add one submit button or a buy button let’s come back and just above this closing form tag we will add one button and button text will be by now you can see this button here next we will Design This so let’s come back to the CSS file here we will add form button in this button we will add the background this color code then we have to change the button text color after that increase the font size of this button text then width it will be 100% and some padding it is 10 pixel and Border radius will be 30 pixel after that we will add border zero and outline Z then we will add margin from the top to add some space from the top and box Shadow here we will add this box shadow then cursor pointer after adding this again refresh the website and you can see this button looks good so we have added all the contents in the product detail section now we will add controls option in the gallery where we will click and change the gallery image so let’s come back and in this Gallery after this image we will add one div with the class name controls inside this div we will add three asan and with this span we will add the class name BTN just duplicate it so we have three span here with the class name BTN next we have to design this one so copy this class name controls write it here in this CSS file here we will add position Position will be absolute then bottom it will be 40 pixel and right it will be 20 pixel so this control buttons will be in the bottom right side of the gallery here we will add BTN so for this span we will add display block and we will add the width and height 10 pixel then we will add border radius 50% so that it will be one small circle then we will add the background so in this background we will add the color code in RGV it will be white colored with 50% opacity then we will add some margin and cursor it will be pointer so here in this controls we have added position absolute so we will add position relative in this gallery you can see we have added Gallery over here at the top so in this one we will add position relative so this control buttons will be in the gallery only after adding this position relative again refresh the website and you can see these three Circle in this product Gallery next we have to add one color in the first one so it will look active so let’s come back and here in this first button we will add one one more class name active after adding this let’s come back to the CSS file at the bottom we will add BTN do active and here just we will change the color let’s add the background and this color code after adding this again refresh the website you can see this blue color in the first dot next we have to add the click function whenever we will click on any other dot the image should change so for that we will add the JavaScript so let’s come back and here in this HTML file we have to add the click feature on this span where we have added class name BTN and we will change the image in this IMG tag so here in this IMG tag we will add one ID also so let’s add the ID product IMG after adding this let’s come back at the bottom just above the closing body tag here we will add a script tag where we will add the JavaScript inside this we will add let product IMG equal to document. get element by ID and you already know the ID which is product IMG next we will add the let BTN equal to document Dot get Elements by class name because we have added the class name BTN in all the span after that we have to add the click feature on the button so here we will add BTN 0. on click equal to function and inside this function we will add the product img.src because we have to change the image so let’s add product img.src equal to the file path of the image so let’s come back to our folder you can see we have one folder called images and inside this folder we have the image called image 1.png 2.png and image 3.png so this is our file path so let’s come back and here we will add images SL image 1 do PNG so this is the first image after adding this let’s duplicate this one and here we will add BTN 1 and BTN 2 for the second button and third button and we will change the image also it is image 2.png and image 3.png after adding this let’s refresh the website again and if I click on the second button you can see the image is changing if I click on the third one image is changing right now the image is changing when we click on these dot but the color is not changing for the dot which is active so we have to change this one we have to change the active color for the circle so let’s come back and here we have added the class name active so we have to remove this class name through JavaScript and this class name will be added in the particular Circle where we will click to remove remve this one we will add for BT of BTN bt. classlist do remove and inside this remove we will add the class name which is active so it will remove the active class name from all the circles so after removing the class name we have to add this class name on the particular Circle where we have clicked for that here we will add this do class list do add and the class name which is active so first it is removing the class name from all the circle and adding the class name on the particular Circle let me copy this one and add it in all the function just copy and paste in the second and third one that’s it again refresh the website and you can see if I click on any Circle the image is changing and the color is also changing when we click on the second one the second Circle becomes blue when we click on the third one then third circle becomes blue so finally we have created this image gallery and product description for this product page I hope this JavaScript course will be helpful for you if you have any question you can ask me in the comment section please like and share this tutorial and also subscribe my channel greatest Tech to watch more videos like this one thank you so much for watching this video

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

  • Learn Git – The Full Course

    Learn Git – The Full Course

    The source provides a comprehensive guide to using Git for version control, aimed at both beginners and more experienced developers. It covers fundamental concepts like repositories, commits, branching, merging, and rebasing, emphasizing practical workflows and best practices. The material explores advanced topics such as resolving conflicts, stashing changes, and using git bisect for debugging. Furthermore, it explains the importance of clean commit history and strategies for achieving it, including squashing. Finally, the lesson introduces worktrees and the power that git has to offer.

    Git Mastery: A Comprehensive Study Guide

    Quiz

    Instructions: Answer the following questions in 2-3 sentences each.

    1. What was the primary motivation behind Linus Torvalds creating Git, and how long did it take him to develop the initial version?
    2. Explain the difference between “porcelain” and “plumbing” commands in Git, providing an example of each.
    3. Describe the three primary states a file can be in within a Git repository.
    4. Why is it important to stage changes using git add before committing them?
    5. Explain why Git is considered a “distributed version control system” and what a “remote” repository is in that context.
    6. Explain how Git optimizes storage despite storing complete snapshots of files with each commit.
    7. What is the purpose of the .gitignore file, and how does it help manage a Git repository?
    8. Explain the difference between git reset and git revert in terms of their impact on the repository’s history.
    9. Describe the purpose of git rebase and how it differs from git merge.
    10. Explain what a Git Tag is and how it’s different from a branch.

    Quiz Answer Key

    1. Linus Torvalds created Git in response to a license dispute with BitKeeper. He created the original version of Git in just five days after Linux lost access to bitkeeper.
    2. “Porcelain” commands are high-level commands used for everyday tasks like git commit, while “plumbing” commands are low-level tools for internal operations, such as git hash-object. Porcelain is what you will use 99% of the time.
    3. A file can be in one of three states: untracked, staged, or committed. Untracked files are not known to Git, staged files are ready to be committed, and committed files are part of the repository’s history.
    4. Staging allows you to select specific changes for a commit, rather than including every modified file. The index is the name for the staging area.
    5. In a distributed version control system, every user has a complete copy of the repository, which is called a “remote.”
    6. Git uses compression and de-duplication to optimize storage. Git compresses each commit to make it smaller and de-duplicates files that are the same across commits.
    7. The .gitignore file specifies intentionally untracked files that Git should ignore. This helps prevent unnecessary files, such as build artifacts or temporary files, from being added to the repository.
    8. git reset moves the current branch to a previous commit. It essentially throws commits away. git revert creates a new commit that undoes the changes of a previous commit, preserving history.
    9. git rebase moves a branch onto another branch, rewriting the commit history. It’s usually good to use git rebase in a private local branch.
    10. Git Tags are immutable pointers to a specific commit. They’re often used to mark release versions.

    Essay Questions

    Instructions: Answer the following essay questions in a well-structured format with supporting evidence from the source material.

    1. Discuss the significance of understanding Git’s underlying plumbing and porcelain commands for effective version control. How does knowledge of both aspects contribute to a developer’s proficiency with Git?
    2. Explore the workflow of Git from modifying a file to having it reflected in the remote repository.
    3. Analyze the various methods of undoing changes in Git, such as reset, revert, and reflog. How do these commands differ, and in what scenarios is each most appropriate?
    4. Explain the relationship between Git and GitHub, clarifying the distinct roles and functionalities of each. How does GitHub enhance collaboration and version control for software development teams?
    5. Describe and contrast different strategies for merging changes in Git, including merge commits, rebasing, and cherry-picking. What are the advantages and disadvantages of each approach, and how do they impact the commit history?

    Glossary of Key Terms

    • Git: A distributed version control system for tracking changes in computer files and coordinating work on those files among multiple people.
    • Repository (Repo): A storage location for all the files associated with a project, along with their history.
    • Commit: A snapshot of the repository at a specific point in time, representing a set of changes.
    • Branch: A pointer to a commit, representing an independent line of development.
    • Merge: The process of combining changes from one branch into another.
    • Rebase: The process of moving a branch to a new base commit, rewriting the commit history.
    • Porcelain: High-level Git commands used for everyday tasks (e.g., commit, add, branch).
    • Plumbing: Low-level Git commands used for internal operations and more complex tasks.
    • Staging Area (Index): A preparatory area where changes are organized before being committed.
    • Remote: A repository hosted on another server or location, allowing for collaboration and sharing of code.
    • .gitignore: A file specifying intentionally untracked files that Git should ignore.
    • HEAD: A pointer to the current branch or commit being worked on.
    • Tag: A named pointer to a specific commit, often used to mark releases.
    • SHA (Secure Hash Algorithm): A unique identifier for a Git object, such as a commit or file.
    • Working Tree: The directory on your file system where the code you are tracking with Git lives.
    • Reflog: A mechanism to record when the tips of branches and other references were updated in the local repository.
    • Squash: Combining a series of commits into a single commit.
    • Stash: Temporarily saving changes to the working directory and index to allow for switching branches or other tasks.
    • Cherry-pick: The act of picking a commit from a branch and including it in another.
    • Bisect: A powerful command that allows one to use binary search to find which commit introduced a bug.
    • Work Tree: The directory on your file system where the code you are tracking with Git lives.

    Boot.dev Git Course: A Comprehensive Review

    Okay, here’s a detailed briefing document summarizing the key themes and ideas from the provided source text, which primarily covers a Git and GitHub course offered by Boot.dev.

    Briefing Document: Boot.dev Git Course Review

    1. Overview

    The source is a transcript of a video course focused on teaching Git version control. The course covers fundamental Git concepts, command-line usage, and team collaboration workflows, and focuses on both theoretical understanding of how Git works internally (“plumbing”) and practical application of Git commands (“porcelain”). The instructor heavily emphasizes hands-on exercises and examples.

    2. Key Themes and Concepts

    • Git Fundamentals:
    • Version Control: The course introduces Git as a system for tracking code changes over time, attributing changes to authors, and enabling history manipulation and reversion.
    • Commits: A core concept is the “commit,” which represents a snapshot of changes tied to an author, timestamp, and message. Git builds a graph of these commits, allowing branching and merging. “git creates a commit a commit is just a set of changes tied to an author time of day and other information.”
    • Branches: The ability to branch off a commit and create new lines of development is emphasized. Branches can be merged, and commits can be squashed or reverted.
    • Staging (Index): The staging area, or index, is explained as an intermediate area where changes are prepared for a commit. The instructor highlights the importance of understanding the difference between untracked, staged, and committed files. “An untracked file means that it’s never been added to the index which is like your staging area or it’s never been tracked”
    • Git is NOT a Delta Store: A key takeaway is that Git doesn’t just store diffs (changes), but rather entire snapshots of the repository at each commit. This was surprising to many, as the instructor notes “This was a surprise to me I always assumed each commit Only Stores the changes made in that commit” Git uses compression and de-duplication techniques to optimize storage.
    • Porcelain vs. Plumbing: Git commands are categorized as high-level (“porcelain”) and low-level (“plumbing”). The course focuses mainly on porcelain commands, as they are used most often in development. “the porcelain commands are the ones that you will use most often as a developer to interact with your code” The source claims the plumbing is the “hard things, the underlying tools you can use with Git” and that if you “understand how the the plumbing works the porcelain makes a lot of sense.”
    • Git Command-Line Usage:
    • Essential Commands: The course repeatedly emphasizes the core commands: status, add, commit, log, branch, checkout, merge, rebase, push, pull.
    • Configuration: Configuring Git with user information (name, email) is covered, along with setting default branch names. The use of local vs. global configuration is explained.
    • Log Flags: The instructor goes over using log in different ways, explaining, for instance, the use of “oneline” and “decorate”.
    • Reset: The git reset command is explained as a means to undo changes, with options like –soft (keeps changes), and –hard (discards changes). The instructor emphasizes the usefulness of git reset –soft in scenarios like rebasing after a mistake.
    • Remote Repositories: The course covers the concept of remote repositories and the standard convention of naming the authoritative source “origin.”
    • Fetch and Merge: The use of git fetch to retrieve changes from a remote and git merge to integrate them into the local branch is demonstrated.
    • Pull: Shows how to pull changes from remote by using git pull origin main, and what to do if you end up with diverging branches
    • Team Collaboration and Workflows:
    • Branching Strategies: The instructor presents branch renaming and branch visualization.
    • Merging and Conflict Resolution: The course addresses merge conflicts, manual resolution, and built-in Git tools like checkout –theirs and checkout –ours.
    • Rebasing: Rebasing is introduced as a method to integrate changes from one branch into another while rewriting the commit history. Squashing changes into a single commit is a common practice before pushing to a public branch, according to the instructor.
    • Pull Requests and Code Review: The course briefly touches upon pull requests and code review workflows, common in team environments.
    • Get Ignore: Explains the usefulness of get ignore files, how to create them, and the usefulness of the exclude parameter.
    • Stashing: A “stack” method, useful for applying some index to a data structure. Also useful if you need to pull new updates.
    • Advanced Git Concepts:
    • Reflog: The git reflog command is highlighted as a tool for recovering lost commits or branches, as it keeps track of HEAD movements. “remember get reflog keeps track of where everything has been”
    • Squashing Commits: The process of combining multiple commits into a single commit is covered, emphasizing its use for clean history and easy reversion.
    • Cherry-Picking: The instructor presents a “cherry-pick” as a method for adding small, specific commits.
    • Bisect: The git bisect command is introduced as a tool for finding the commit that introduced a bug through automated searching. It requires a programmatically informed test.
    • Worktrees: Briefly mentions the importance of work trees.
    • Tags: Emphasizes that tags are immutable pointers, so you cannot make edits to a tag.

    3. Notable Points and Opinions

    • Instructor Personality: The instructor has a casual, humorous style, often interjecting personal anecdotes and opinions.
    • “The Right Way” to Use Git: The instructor often presents a particular way of using Git as the “best” or “correct” way, though acknowledging that other approaches exist.
    • Emphasis on Understanding Git Internals: The course attempts to go beyond just teaching commands and aims to provide a deeper understanding of how Git works “under the hood.”
    • Criticism of Lane: The author is critical of “Lane” for his comments, which can be seen as copy-editing.
    • Reference of Popular Culture: References popular culture, such as “Star Wars”, “Slanderous” and “Ren and Stimpy”.

    4. Potential Improvements

    • More structured presentation of advanced topics.
    • More emphasis on different branching models (Gitflow, GitHub Flow).
    • More detailed explanation of the interplay between the working directory, staging area, and commit history.

    5. Conclusion

    The Boot.dev Git course appears to be a comprehensive introduction to Git, covering a wide range of topics from basic usage to more advanced concepts. The instructor’s emphasis on hands-on exercises and theoretical understanding makes it a valuable resource for aspiring developers, although the opinions and informal style might not be for everyone.

    Git: Frequently Asked Questions

    Frequently Asked Questions About Git

    Here are some frequently asked questions about Git, based on the provided source:

    1. What is Git and what does it allow you to do?

    Git is a distributed version control system that allows you to track changes to code over time, by author. It provides commands to search, manipulate, and revert history. Essentially, it creates snapshots (commits) of your code, tied to an author, timestamp, and other relevant information. You can branch off from any commit, create new commits on these branches, and merge them back together.

    2. Who created Git and why?

    Linus Torvalds, the creator of Linux, created Git in five days in 2005. This was triggered by a license dispute between Linux and BitKeeper, a commercial version control system that Linux had been using. Someone reverse engineered the BitKeeper protocol, and as a result Linus created Git for the Linux kernel development. Git was initially not user-friendly, requiring the use of low-level (plumbing) commands.

    3. What is the difference between “porcelain” and “plumbing” commands in Git?

    Git commands are divided into high-level (“porcelain”) and low-level (“plumbing”) commands. Porcelain commands are the ones developers use most often for interacting with code. Examples include git add, git commit, git branch, git merge, and git rebase. Plumbing commands are the underlying tools that Git uses, such as git apply, git commit-tree, and git hash-object. While understanding plumbing can be helpful, developers typically use porcelain commands 99% of the time.

    4. What are the key states a file can be in within a Git repository?

    A file in a Git repository can be in several states:

    • Untracked: Git doesn’t know about the file, meaning it has never been added to the index (staging area) or committed.
    • Staged (Indexed): The file has been added to the staging area, meaning it is ready to be included in the next commit. Only the changes added are tracked.
    • Committed: The file is part of a snapshot stored in Git’s history.

    5. How does Git store data, and what are “trees” and “blobs”?

    Git stores data as objects in the .git/objects directory, compressing them to save space. A commit is a type of object that includes a hash, author, timestamp, and message. Git doesn’t store diffs; it stores entire snapshots of files per commit.

    • Tree: Represents a directory in Git.
    • Blob: Represents a file in Git.

    A commit contains a tree object representing the root directory. This tree can contain other trees (subdirectories) and blobs (files). This structure allows Git to recreate the state of the repository at any point in history.

    6. How do you configure Git with your personal information?

    You can configure Git with your name and email address using the git config command. This information is stored in a configuration file, which can be either global (located in your home directory) or local (located in the .git folder of your repository). For example:

    git config –global user.name “Your Name”

    git config –global user.email “your.email@example.com”

    You can also configure the default branch name, setting it to main instead of master.

    7. What is git reflog and why is it useful?

    git reflog is a mechanism to record when the tips of branches and other references were updated in the local repository. The reflog allows you to recover commits even after branches have been deleted or lost. It keeps track of where “HEAD” (the pointer to the current commit) has been, making it possible to revert to previous states.

    8. What is git bisect and how can it help with debugging?

    git bisect is a powerful command for finding the commit that introduced a bug. It works by performing a binary search through the commit history. You mark a known “good” commit (before the bug existed) and a “bad” commit (where the bug is present). Git will then check out commits in between, and you mark each commit as “good” or “bad” based on whether the bug is present. Git bisect continues this process, narrowing down the range until it identifies the specific commit that introduced the bug. You can use it to check if a current commit is good or bad.

    Git bisect can even be automated with a script that programmatically determines if a commit is “good” or “bad.” This is done with get bisect run <script>, and by returning a non-zero exit code will designate it as bad, and zero will designate it as good.

    Git Version Control: Concepts and Commands

    Git is a Version Control System that allows you to track code changes over time by author. It was written by Linus Torvalds in 5 days and has become the standard for developers.

    Key aspects of Git include:

    • Repositories Each project has one repository, which is essentially a directory containing the project and a hidden .git directory. The .git directory stores the entire state of the Git project. To create a new empty repository, you can use git init.
    • Commits Git creates commits, which are sets of changes tied to an author, time, and other information. Git stores the entire history per commit.
    • Porcelain and Plumbing Git commands are divided into high-level (porcelain) and low-level (plumbing) commands. Porcelain commands are used most often by developers.
    • Configuration Git can be configured with your information using the git config command. The configuration file is a file that can be in global space (your home directory) or within your .git folder.
    • States Files in a Git repository can be in several states including untracked, staged, and committed. The git status command shows the current state of the repo. An untracked file has never been added to the index or tracked.
    • Staging Area The staging area is also known as the index.
    • Tracking Changes You can add a file to the staging area using the add command. After staging a file, you can commit it. A commit is a snapshot of the repository at a given time. The git log command shows a history in a repository.
    • Branches A branch is a pointer to a commit. Branches are lightweight and cheap. You can determine which branch you’re currently on with git branch. It is recommended to use main as your default branch if you work primarily with GitHub.
    • Merging Merging is bringing work from a branch back into the main line. A merge commit is a new commit that represents two diverging histories as one. It is the only commit with two parents.
    • Remotes A remote is another repo. Git is a distributed Version Control, so each repo is its own repo, and you sync between them.

    Git Branching: Management and Merging Strategies

    Branching in Git allows you to keep track of different changes separately. A branch is essentially a pointer to a commit. Because branches are simply pointers to commits, they are lightweight and cheap.

    To see which branch you are currently on, use git branch. It is recommended to use main as your default branch if you work primarily with GitHub.

    Key aspects of branch management:

    • Creating a Branch You can create a new branch using get branch New Branch name. However, it is more common to create and switch to a branch at the same time using git checkout -b <new_branch_name> or the newer command git switch -c <new_branch_name>. When you create a branch, it takes your current location and that’s where it points to.
    • Switching Branches To switch to an existing branch, you can use git switch <branch_name>. Older versions of Git used the command git checkout <branch_name>.
    • Deleting a Branch After a branch has been merged into main, it can be deleted. To delete a branch, use the command git branch -d <branch_name>.
    • Visualizing Branches Branches can be visualized as a series of commits. For example, a branch called main with three commits (A, B, and C) would be represented as A -> B -> C, where C is the most recent commit. If a new branch called other_branch splits off from A, it might have commits D and E, resulting in diverging branches.
    • Merging Branches Merging is integrating changes from one branch into another. A typical workflow involves branching off the main branch, making changes on the new branch, and then merging those changes back into the main line. This often involves a pull request on platforms like GitHub, GitLab, or Stash.
    • Merge Commits When merging branches with diverging histories, Git creates a merge commit. This commit represents the combination of the two histories and has two parent commits. The process involves finding the merge base (the nearest common ancestor of both branches), playing the main branch’s commits into a new commit, and then playing the other branch’s commits into that same commit.
    • Fast-forward Merge A fast-forward merge occurs when the branch you are merging onto has all the commits that the other branch has. Git simply moves the pointer of the base branch to the tip of the feature branch.
    • Rebasing Rebasing and merging can both be used to integrate changes from one branch into another. Rebasing rewrites Git history, which can be dangerous if not done carefully.
    • Git Reflog Git reflog keeps track of where everything has been. It can be used to recover commits on deleted branches.

    Git Merge Conflicts: Resolution and Management

    Here’s a discussion of merge conflicts, based on the sources:

    A merge conflict arises when two commits modify the same line in a file, and Git cannot automatically decide which changes to keep. This typically happens during a merge or rebase operation. Git identifies conflicted files and prompts you to resolve the conflict manually by editing the files.

    Key aspects of merge conflicts:

    • Causes A merge conflict typically occurs when changes are made to the same lines of code on different branches, and these changes are not direct descendants of each other. If the same line is modified in one commit and then again in a later commit, Git can usually resolve this automatically because it knows the order of changes. However, when two developers on separate branches modify the same line, a conflict arises when merging those branches.
    • Resolving Conflicts Resolving merge conflicts is a manual process. Git marks the conflicted files and asks you to resolve the conflict by editing the files in your editor.
    • Conflict Markers When a conflict occurs, Git adds conflict markers to the file to show the conflicting changes. These markers include <<<<<<< HEAD, =========, and >>>>>>> branch_name. The section between <<<<<<< HEAD and ========= represents the changes in your current branch (HEAD), while the section between ========= and >>>>>>> branch_name represents the changes in the branch being merged.
    • “Ours” and “Theirs” In a merge conflict, “ours” refers to the branch you are currently on and merging into, while “theirs” refers to the branch being merged. When rebasing, it can be the opposite.
    • During a rebase, the target branch becomes the branch you’re on, and then Git replays the source branch’s commits starting from the merge base forward to the tip of your target branch.
    • Therefore, during a rebase conflict, “ours” is “theirs” and “theirs” is “ours”.
    • Accepting Changes To resolve a conflict, you must edit the file, remove the conflict markers, and decide which changes to keep. You can choose to accept both changes, keep only your changes, keep only the incoming changes, or modify the code to incorporate both.
    • Built-in Merge Resolution Tools Git provides built-in tools to help resolve conflicts. The git checkout command can check out individual changes during a merge conflict using the –theirs and –ours flags.
    • Post-Resolution Steps After resolving the conflicts, you must stage the changes using git add and commit them to continue the merge process.
    • Re-recording Resolution Git has a “re-recording resolution” feature (re-re) that allows it to remember how you resolved a conflict. If enabled, Git can automatically resolve the same conflict the next time it occurs. To enable this feature, you can run git config –global rerere.enabled true.
    • Accidental Commits During Rebase If you accidentally commit during a rebase, you can use git reset –soft HEAD~1 to undo the commit and continue the rebase. This command moves the branch back one commit while keeping the changes in your working tree.

    Git Rebasing: Strategies, Use Cases, and Best Practices

    Here is a discussion of rebase strategy, drawing on the sources:

    Rebasing is a Git operation that helps integrate changes from one branch into another by moving or reapplying commits. It is an alternative to merging, and is often used to maintain a cleaner, more linear project history. However, it can rewrite Git history, which can be dangerous if not done carefully.

    Here are key considerations for a rebase strategy:

    • Primary Use Case The primary use case for rebase is to take the diverging commits from one branch and move them to the tip of the base branch that the feature branch is based on. This allows for a fast-forward merge back into the main branch.
    • How Rebasing Works When you perform a rebase (e.g., git rebase main on a feature branch), Git checks out the target branch (e.g., main). It then takes the changes from the source branch (feature branch) and applies its commits to the tip of the target branch. Finally, it updates the source branch to point to the new tip.
    • Linear History Rebasing allows you to maintain a merge commit-free history. A linear history is generally easier to read, understand, and work with.
    • Commit Shas During a rebase, even if the commit message is the same, you will get new commit Shas. This is because the parent of the commit is no longer the same.
    • Conflicts If there was a conflict while rebasing, there would be a conflict while merging.
    • Rebase vs Merge Both rebase and merge can be used to integrate changes from one branch into another. Merge can add an additional commit, while rebase does not.
    • When to Rebase It is generally okay to rebase your private branch on top of a public branch. If you’re working on your own branch and want to undo something you’ve already committed, git reset is preferable.
    • When NOT to Rebase You should never rebase a public branch like main. Doing so can cause significant issues for other collaborators. It’s generally good practice to rebase a public branch onto your own personal branch.
    • Rebase and Fast-Forward Merges Rebasing allows you to move a feature branch forward from diverging at a point up to diverging off of the current tip of the main branch, allowing for a fast-forward merge if you wish to get it back into main.
    • Interactive Rebasing Git rebase interactive is very nice and is used for squashing.
    • Rebase –continue If you make a mistake and commit changes (rather than calling git rebase –continue), you can use git reset –soft head~1 to undo that commit and then rebase –continue.
    • The “Ours” and “Theirs” During Rebase During a rebase, it is important to remember that “ours” is “theirs” and “theirs” is “ours” during a rebase conflict. The target Branch becomes your branch that you’re on, and then you replay the source branches commits starting from the merge base and forward at the tip of your target Branch.
    • If you had merged main instead of rebase, HEAD would still point to your branch.
    • Git Rerere Git has a “re-recording resolution” feature (re-re) that allows it to remember how you resolved a conflict. If enabled, Git can automatically resolve the same conflict the next time it occurs. To enable this feature, you can run git config –global rerere.enabled true.
    • Squashing
    • Squashing is used to combine a series of commits into a single commit. This is often done to clean up the Git history.
    • To squash the last n commits, start an interactive rebase with get rebase -i HEAD~n. In the editor that opens, change the word pick to squash (or s) for the commits you want to squash into the previous commit.
    • After squashing, you can edit the commit message.

    Undoing Changes with Git: Reset, Revert, and Amend

    Here’s a discussion of undoing changes in Git, drawing on the sources:

    Git provides several ways to undo changes, ranging from simple operations on your local branch to more complex maneuvers for shared branches. The right approach depends on the situation, such as whether the changes are only in your local repository or have been shared with others.

    Methods for Undoing Changes

    • git reset: This command is a powerful tool for undoing commits or changes in the index. It has three main options:
    • –soft: This option is useful if you want to go back to a previous commit but keep all your changes. The committed changes will be uncommitted and staged, while uncommitted changes will remain as they were. It takes the commits changes and applies them to your work tree, and moves your branch back once.
    • –hard: This option not only undoes the changes and moves your branch back, but it also clears out your index and working tree. Any uncommitted changes will be lost. This option should be used with caution, as it can lead to data loss.
    • git reset commit_hash: To reset back to a specific commit, you can use git reset –hard commit_hash. This will reset your working directory and index to the state of that commit, and all changes made after that commit will be lost.
    • git revert: This command is used to undo changes on a shared branch. Instead of removing the commit, it creates a new commit that does the exact opposite of the commit being reverted. This keeps the full history of the changes and undoing.
    • To revert a commit, you need to know the commit hash. You can find this using git log. Then, use the command git revert <commit_hash>.
    • git checkout: The git checkout command can check out individual changes during a merge conflict with the –theirs and –ours flags.
    • git commit –amend: Can be used to change the last commit’s message, but it does change your SHA.

    Scenarios and Best Practices

    • Local vs. Shared Branches:
    • If you’re working on your own branch and just want to undo something you’ve already committed, git reset is generally the way to go. This is useful for cleaning up commits before opening a pull request.
    • If you need to undo a change that’s already on a shared branch, especially if it’s an older change, git revert is the safer option. It avoids rewriting history and stepping on your coworkers’ toes.
    • Rebasing: If you make a mistake and commit changes (rather than calling git rebase –continue), you can use git reset –soft HEAD~1 to undo that commit and then rebase –continue.
    • Untracked Files: git reset –hard will not affect untracked files because they have not been added to the working tree yet.
    • Accidental Commits During Rebase: If you accidentally commit during a rebase, you can use git reset –soft HEAD~1 to undo the commit and continue the rebase.
    • Reset after a mistake: A soft reset is an amazing thing to use and it becomes exceptionally good when you screw up a revert, cherry pick, or a rebase.

    Dangers and Precautions

    • Rewriting Public History: Never rebase a public branch like main because it destroys your life.
    • Losing Changes: Be very careful when using git reset –hard, as it can lead to irreversible data loss.
    • Force Pushing: Never force push to master.
    • Accidental Deletion: If you were to simply delete a committed file, it would be trivially easy to recover because it is tracked in git. However, if you use git reset –hard to undo committing that file, it would be deleted for good.
    Learn Git – The Full Course

    The Original Text

    93% of developers use git which actually feels to me a little bit low because 100% of the developers that I’ve worked with use git it’s got a tighter grip on the Version Control industry than Google does on your personal data in this video the prime engine is going to walk you through not one but both of his git courses I’ll try to keep this intro short because Prime does a better job of talking in front of the camera than I do but I just wanted to let you know what you’re getting into now in each course there are 11 chapters which means 22 chapters in total you’ll learn how to set up git what repositories are get internals get configs branches how to merge how to rebase get reset what remotes are how to use GitHub with Git and ignoring files with G ignore in the second half of the course you’ll learn how to Fork AO how to use ref log merge conflicts rebase conflicts squashing stashing reverting cherry-picking get bisect get work trees and tags it’s a lot the first half of this course primes course number one is really all about learning how to use git as a solo developer and course number two covers all the stuff you need to know to use git effectively in a team Prime has spent over eight months writing these courses and the rest of the boot de team and I have spent that same amount of time really helping to edit test and refine them so I hope you enjoy them but this is a very Interactive Ive course I do not recommend sitting down and binging it in one sitting there are interactive lessons and projects the entire way so get your hands on the keyboard and actually follow along in fact I actually recommend that you take the course on boot Dev and go ahead of prime and then watch him go through that same lesson so you can see his approach his commentary and his Solutions after you’ve had a chance to experiment and and challenge yourself and do it yourself now all of the content in this YouTube video and all of the content on bootd are completely free there’s no need to sign up for a boot Dev membership to get value out of this course that said all of the interactive features on buev are paid features so if you want to be able to submit your own assignments if you want to view Solutions chat with the AI chatbot or get a certificate of completion at the end uh you will need a paid membership for that and you can actually use primagen code Prime YT that will not only help us at boot dev be able to produce more courses like this but that also supports the prime engine directly that code Prime YT will get you 25% off your first month or year if you choose an annual plan of a boot dodev membership one last note if you get stuck and need help our Discord Community is literally just a few clicks away so join the Discord Community ask for help and let’s talk about get all right we are now going to officially start the entire boot dodev learn get I’m going to go through my I’m going to go through the course that I created I want to do it and it’s going to be awesome here we go we’re going to go through the course we’re not going to watch the videos because guess what this is my course in 2005 after license disputes with bitkeeper lonus Tal’s creator of Linux you may have heard of it sort of runs the web not a big deal decides to write his own Version Control he wrote git in 5 days and within a couple years it became a widely used Version Control and now today it is the de facto standard for all developers to be clear when I say get I don’t mean an insult from across the pond and I don’t mean GitHub gitlab stash or any of the others all of those companies use git they are not git git allows you to track code changes over time by author with a set of commands to search manipulate and revert history in simple term git creates a commit a commit is just a set of changes tied to an author time of day and other information as many commits as you want can be added to the graph at any commit you can Branch off and create new commits on the new line any of these branches can be merged into any other Branch including the main line commits can be squashed into one commit and commit messages can be edited also git commits can be reverted just in case they don’t want terrible code git is very complicated piece of software but the interface and operations are very simple and in this course we’re going to be going over installing and configuring get porcelain in plumbing commands inspecting G history branching merging and rebasing undoing changes and remote repos and GitHub I hope you enjoy this course and in about another month or two I will be releasing part two which will go over all the advanced features Advanced Techniques with merges and rebases and conflicts and of course just really diving into some of the more complex parts of git but in this course you should be able to get everything you need to become quite proficient in the real world incl including understanding how git works the name is the gagen I already have everything done I might need to update boot dodev hold on one second all right there we go I’m going to get the latest version here we go go install I thought they I thought that was a thing H anyways okay there we go we got the new boot dodev everything’s looking good let’s do a little boot Dev version oh yeah looking hot looking good perfect I believe I should all be logged in so I’m just going to go like this just to make sure that I’m logged in there we go echoing rebasing his base there we go everything good I believe I’m I believe I’m all good perfect okay submit so this is the cool part by the way so this tool was developed I think the motivation started with my course and other courses I think Lane was developing one that also needed it as well but this tool is super cool so you copy this thing you paste it in and when you go right here look at that it says hey you did everything correct okay fantastic all right we’ve already installed git I already have everything installed I don’t need to worry about any of that all right we’ll do that thing as well okay perfect the CLI is so cool it is all right read the friendly manual one of the best parts of G is that all the documentation is fantastic but that wasn’t always the case by the way it was actually the the git documentation to this day I actually can’t read the uh man G tag page still okay so everybody knows what a tag is right we all know what a tag is a let’s see add a tag reference in ref tags unless DV dlv is given to delete list or verify tags um okay okay I think we understand this right unless f is given the named tag must not yet exist and then this is happened to create a take object or requires take message unless M or f file is given and editor is started for the user okay what the hell is a tag though can you just tell me what it is otherwise a tag reference points directly to a given object I know it’s just like is this just a wild I’m surprised the very first description isn’t being like a tag is a mut a immutable named pointer I’m just like what the fu is this all right who created get obviously I did a by the way lonus tvols did create git in 5 days and The Story Goes Like This he created git in five days because one of the one of the maintainers of Linux broke the bitkeeper license to Linux bitkeeper said you can use bitkeeper you’re just not allowed to reverse engineer the protocol and somebody reverse engineered the protocol and get and bitkeeper said get the hell out of here get out and so they actually had no more uh subversion at that point or whatever bitkeeper was so he wrote to in 5 days now remember git was not friendly at all you had to use all the plumbing right you had to use like you had to like cat out the file you had to create the tree like you had to do all the tracking yourself and it was not fun right it was not good it was not good but anyways lonus did it all in just a moment and he did it in five days then on the sixth day he rested porcelain and plumbing for whatever reason get is compared to the crapper uh rip John crap and so porcelains the outside the good stuff uh the plumbing is like the hard things the like the underlying tools you can use with Git all right so in get commands are divided into highle commands and lowl commands the porcelain commands are the ones that you will use most often as a developer to interact with your code some porcelain commands are these on don’t worry about what they do yet we’ll cover them in detail soon absolutely by the way some examples of Plumbing are this one get apply give get commit Tre get hash object in which I barely know any of what those things do we’ll focus on the highle commands because that’s what you use 99% of the time in fact I’ve never professionally use the lower level commands right BCT is I I I believe is a porcelain command um reflog porcelain command cherry pick porcelain command it’s a bit confusing right all right 99% of the time porland commands are used to interact with Git yeah but you can and I have done it but it’s really good to understand how they work if you understand how the the plumbing works the porcelain makes a lot of sense all right quick and fig we need the configure get uh with your information uh whenever you code yeah blah BL blah blah blah so we got to do this thing we got to add our name in our config so if you’ve never done config and get get just has this whole Global it’s literally just a file that’s all it is is just a file and it’s either in global space which means it’s in your uh home directory or it’s within yourg fer so kind of either or there anyways this is pretty good so we can uh we can do this config set username email so I’m going to make sure let’s see uh get config uh local what do I got here oh whoopsies uh is it List local I always forget how to use this one air keys does not contain get config what what what is it it’s it’s list oh yeah I forget list is the only one config is the only one that has this older way of doing a bunch of Dash dashes whereas like when you use something like get stash you go like get stash list whereas with config you go this kind of list and always it always I always have to remember what the hell I’m doing right there okay local so as you can see I have all these things these are all the good stuff this is uh from graphite so don’t don’t mind that here we’re going to probably want to do stuff little get config uh list GP name do I have a name in there I do I have the name uh there we go I have email perfect bada bing bada boom we got those things already set so I have all that and you add it to your Global so your you’re Global by the way if you just go like this you can go uh whoopsies get config right it’s right there it just takes the latest value all right and so we also have this one finally let’s set the default Branch we’ll talk more about this so we’re all on the same page we’re going to set the default Branch to master to begin with so the funny part is is that um hey hey now let’s see hey now Global and then you have to go uh what is it is it add look at that there we go add there we go so it takes the latest one probably need to do an ad might want to make a little note there never caught that problem only level two week I had to reset my entire account all right make sure it works so there’s a reason why we do this so we can show you to do it differently later right but it’s Master by default true but a lot of people already have it say updated to main or to trunk or something else so I just wanted to make sure that we had this such that everybody can change it um and see what it is so there you go all right so we can C the config awesome you saw that we CED the config everything looks good all right we’re going to kind of rush through these early ones because I don’t think they’re very they’re not that important and when you’re learning how to use git these ones don’t make a lot of sense like what the heck is this config thing why are we setting all these things we just got to do it to set up your repo so you understand how git works right so this is all confusing stuff you’re probably very confused if you’re new to get that’s fine it’s [Music] okay all right so all right the very first step uh of any project is to create a repository a get repository or repo represents a single project you typically have one repository for each project you work on it would be wild to see many repositories for a single project unless if you’re considering uh Forks SL yeah webflix you like that a repo is essentially just a directory that contains a project other directory or files the only difference is that it also contains a hidden git directory this was a big eye opener for me is realizing that the that the dogit is literally the entire state of your G project it’s like the entire thing and so if you’re ever having questions about what’s going on everything is actually stored in here so when you think oh how does it know every like how does it know all my branches it’s literally in the git directory everything about it is in the git directory uh webflix this uh this course we’ll be managing content for webflix an imaginary self-hosted video streaming application can you imagine why would why would we name it webflix that makes no sense let’s see navigate to somewhere in your file system where you’d like to store the project and once you’re there create a new directory called webflix all right uh rmrf I bet you webflix already exists in my oh my gosh get the hell out of there oh get the hell out of there okay makeer webflix there we go and webflix there we go now I’m in here it’s brand new right it’s empty nothing in here and so I’m I’m assuming we’re going to have to get init get init just creates the new empty directory right it doesn’t do anything other than it creates a brand new directory it uses our config let’s go so I should be able to go ls- la you can see a git folder right here if I find inside the git folder it’s pretty empty it just has all this stuff it has a bunch of sample preh hooks it has no objects which is where it stores everything it has uh nothing I believe even the head is a little bit goofy if I’m not mistaken there you go that was weird cat get head there you go weird huh getting it yeah all right so anyways we do all this one awesome so now that we have our uh repo initialized let’s actually get into the stuff is this VOD G stay online it’s actually going to be moved to the uh boot dodev YouTube there we go we got all this this looks good let’s go return to our browser done got him man I’m so good at this I’m getting so much stats look at this I’m already level two a file can be one of the several States let’s see a file can be in one of several States in a get repository here’s a few important ones untracked staged committed okay this is very important this is also very important to understand because I’ve lost so much work not understanding the difference between all of these all right the get status command shows you the current state of your repo all right so assignment every good content management system needs a table of contents create a file in your rout called contents. MD and add the following lines let’s do this all right Vim contents. MD d uh paste this thing in Bam Bam get status you’ll see right here untracked files that means git doesn’t know anything about this this file an untracked file means that it’s never been added to the index which is like your staging area or it’s never been tracked so it just says we don’t know what’s in it so if you delete this file you lose every last bit of content because I’m pretty sure there’s been a lot of people that have goofed that up yeah I’ve done it it hurts it’s emotionally a bruising experience to accidentally have a file that was untracked you think it’s tracked you do something and you delete it and Fs you removed untracked files yeah removing untracked files is is emotionally painful because you can’t really recover it it’s a right of passage it’s a right of passage to emotionally bruise yourself all right there we go so now I should be able to jump in here I should be able to run the little tool there we go everything’s good all right so staging staging you’ll notice the term index a lot so if we go into here and we go mangit uh what’s it called add you’ll probably notice the word index quite a bit in here and the index is literally just the changes that you have staged onto your system that means any untracked files become tracked files and only the entire changes are tracked at that point there we go uh add this one let’s see for example I use Arch by the way right without staging every file in the repository would be included in every commit but that’s often not what we want all right so you want to get add the file so I’m going to add the contents and then do this now me personally whenever I do stuff I usually hit a get status if the tree represents what I want it to be meaning that the changes are what I want and we have just this one untracked file I often will just use get add this now here’s the deal about get ad okay that’s a little goofy all right uh get status uh when you do this here I’m going to go like this I’m going to go touch Fu if I go like this get status you’ll notice that Foo is untracked as well if I make her uh Fufu and CD into Fufu and then get add this you’ll notice that Fu remains untracked that’s because get add dot adds everything at that directory and Beyond it doesn’t add it doesn’t add things in the directory P you have to use different ones like get add capital A that kind of stuff but we’re not talking about that okay we’re not talking about that uh there you go get get the hell out of here there we go status we got that fantastic um so I should be able to just run this we’ve now added it our contents have been added we’re looking good we’re looking good oh man I’m getting so much experience points I I’m I’m almost level three after staging a file we can commit it a commit is a snapshot of the repository at any given time so this is very very important and this is a thing that a lot of people don’t understand about git git is not storing diffs git stores the entire history per commit so your entire git everything is in a single commit and that’s very very important distinction to make because a lot of people don’t realize that okay so our assignment is commit the contents to file this with the message add contents this you would normally start a commit message with a obviously this is because we’re doing stuff with boot dodev so it wants to be able to keep track of all your commits and all that so there we go then run get status skin you should see that the file is no longer staged right all right so let’s go back here uh let’s zoom in uh get commit let’s see uh get commit there we go we did that and so if we go get status you can see we have a clean working tree get log one line You’ll see that we have one thing right there let’s see wait it so it doesn’t store per change commit no and density I’ll show you why in just a moment so this course is meant to really show you what is going on here all right so now that we have that I should be able to just take this boot. Dev paste that in there go right here awesome I did it I’m I’m smat I’m smat I’m real smat uh half of git you’ve learned half of G you’ve literally learned half of git we just get commit status add commit right that’s all you need to know status add commit that’s like most of I know that’s crazy to think of but that’s it half of G easy you’re like you’re like a senior engineer at this point it’s not near half though I know of course it’s not actually near half because when you go like this get uh uh when you go like this man get Dash you’ll notice that there’s 151 possibilities but of those possibilities three of them is what you pretty much use constantly which commands adds a file to the staging area Prime is it Prime no add right it’s in the name dummies it’s in the name name dummies all right get log get uh okay log is fantastic by the way log is one of those sleepers that people don’t know how to use but there’s so many good stuff to a log get repo is a potentially very long list of commits where each commit represents a full state of the history a git log command shows a history uh in a repository this is what makes get a Version Control System you can see who made the commit when the commit was made and what was what was changed so there’s a lot of cool things so here so this right here so they we’ll see what uh he made us do this goes get no pager I believe this just simply will output the git log so normally when you do git log it actually outputs this like second screen that’s kind of like less if you’ve ever use the Tool uh less that’s all it’s doing instead no pager just prints it directly out it just prints it to standard out and log is the command N1 means the last 10 commits but what you really want to do is you want uh you can do things like one line that will make it nice and smooth so you can just see this nice beautiful thing you can do uh parents which will do annotation we don’t have any parents yet we don’t got no parents we are the Batman of commits uh and you there’s a bunch of stuff graph is really cool if you’re working on something cuz graph is you’ll notice that there’s like a little Aster right here it will actually graph how your commits are being merged back in and how the uh different branches are going so we’re orphans right now we’re effectively orphans right now or you can think of us like Adam maybe we’re the first huh it’s not that bad right right all right do the one of those there we go bada bing bada boom all right so let’s get into some real stuff different hashes my latest commit uh or so in this example the commit hash was this our commit hash was what 78 blah blah and that’s because whenever you do anything with Git the hashes can’t you can technically do a hash collision by being able to generate the same git changes from the same author at the same time and whatever other information that it uses with the same parent and all that you could actually create the the hash is consistent it’s recreated every single time so it’s an important Point all right there we go if you’re not careful you’ll have two commits with the same hash false you’d have to be very careful to create that and I don’t believe that’s even a uh it’s not even like a yeah g is the original blockchain for those that are wondering all right you may have noticed that even though we you and I both have the same content in our repositories we have different hashes yes we already went through all this yes they do a sha one it’s beautiful which does let’s see which does not affect the uh the hash of a commit the commit time stamp message author’s preferred text editor even though it should I do think all Vim hashes should start with 777 a little bit of luckiness to it to me that’s the only appropriate thing to do all right the plumbing so far we’ve used git in a porcelain manner but the let’s see but to Sate our insatiable curiosity Sate is a weird word okay Lane may have done a little bit of writing for me in this one just so you know uh let’s take a look at the plumbing all right it’s just files all the way down all the data in the git repository is stored directly in the hidden file you can actually see that look at this if I go like this if I go find inside the git folder you’ll notice something right away look at this look at that thing that thing looks just like this thing right here right 7805 172 7805 172 look at that huh kind of crazy right that’s my commit okay sneaky git very Shakespearean I know he’s very Shakespearean he uses phrases like upstairs and downstairs and it’s crazy all right git is made up of objects that are stored in the git objects directory uh a commit is just a type of an object correct use log 10 to view your commit hash do this inside the object directory and we already did that we already saw it which uh let’s see which matches the format of the file you’ll notice here too so this is something that you probably don’t know about Linux uh this right here this is called an inode busting effectively what IOD busting is is that a directory can actually end up having too many files in it if you ever done it weird stuff starts happening happen happening so instead get to prevent iode busting or to prevent iode whatever it is you’ll do this so this takes the first two letters and then does this right i’ I’ve ran out of iodes before yes I i’ I’ve goofed up myself so a directory can only be such a large size so therefore this just helps separate out things this is very common you’ll see this in CDN cdns do the exact same thing the actual naming underneath will start doing weird stuff like this screw you unlinks your list yeah it is it I’ve done it once I dude I note issues are insane by the way they’re crazy yep I ran into this with a massive log directories exactly you have to do I note busting or else you just life is painful and I did it once and then once you do it once you never do it you just never do it again all right that’s it that’s all there is to it all right so that’s why they do this they take the first two and they turn it into a directory so that way it just kind of spread things out all right so let’s take a uh let’s take a look at what’s inside this suspicious get commit object file have you ever tried catting one of those things the first thing I ever did when I found out get was just a folder is went right to objects went right to my commit and tried to cat it out and it’s just this right that’s a bunch of right there okay what the hell does this even mean all right so you can’t really do anything no it’s a mess uh let’s see the contents have been compressed to Raw bites so that’s why git remains small is because git compresses things and that’s very very important all right now the lesson let’s see okay hold on this lessons run and submit are a bit different because you need to tell boot. Dev CLI where your commit object is located all right so we’re going to do the exact same thing so I have to do this but I have to give it this name right path to file right so I’m going to grab this thing and I’m going to go like this uh let’s go get objects 7805 05 this thing and then submit I believe I did that correctly this one I screwed up last time I tried to do this let’s see failed to get this thing page not found wait who’s he what’s he all right let me reread this one sorry sometimes sometimes I’m not good at reading lessons Okay I just want you to know that rtfm read the friendly manual sometimes I don’t read the friendly lesson okay let’s look at this again try to C the contents of the file we already did that nope it’s a mess the contents has been compressed um we can we can print in a decimal I don’t really care this lessons run and submit are a bit different because you need to tell boot. CLI where your commit object is located uh run and submit the test but provide the path to your commit object file as a second argument run lesson lesson ID okay so let’s try this again because I’m apparently I’m too stupid so I need to go boot. run lesson ID path to file okay get objects 78 052 there we go look at that I’m getting so much exp I’m level four you guys wouldn’t understand practically a grand wizard Arc Mage I don’t think you’re supposed to be a grand wizard right that’s not uh you don’t want to be that you don’t want to be that guy okay I forget sometimes I forget things okay uh luckily git has a built-in Plumbing command cat file that allows us to see the contents of a commit without needing to fuss around with the object files directly so you just use get cat file- P cuz technically like if you’re viewing a tree you have to use a tree command you know there’s all these different things but cat file just allows us to look at everything at once without having to worry about its type and all that uh so you can just go get CAT file this so if I do this get cat file this guy and do 78517 I believe you only need up I think you only need technically you only need four to specify it you’ll notice something when I cat out my commit you’ll see the author and all this and then you’ll see the message that’s so it’s nice then you see this tree command look at this tree this hash we don’t know what this hash is right so I can actually go get uh get cat file- P 5B 21d and then you’ll notice that it has a blob object and that blob object is a Content so to kind of put this in perspective you can think of a tree as a directory and you can think of a blob as a file so that’s kind of important to know so when I cat file this thing you’ll notice that it’s contents which is the exact contents of our contents file they’re identical so do you see what happened there why did I capitalize B for those that don’t know why I capitalize B uh when I type I have dvorac but even more so when I type numbers 1 2 3 4 5 6 7 8 9 10 you’ll notice that I typed out symbols symmetric symbols it’s because I’ve optimized my keyboard to prevent wrist pain from happening because I program a lot so I have to hit shift to type my numbers right so sometimes I’ll do a capital B when trying to type stuff because I’m still holding shift does that make sense okay there’s no there’s no reason or Rhyme or anything to do with it it automatically lowercased it for me it didn’t mean anything all right so there you go you can see that so this is actually really cool what just happened here look at this I was able to cat my commit out take the root directory tree cat that out see the file that was there then cat that file out and see the contents of that file this is very important because we’ll use it later to grab stuff out it’s kind of fun it’s kind of it’s kind of neat so there we go so we can do that all right so use cat to do all this one pass an argument to the CLI notice that boot. Dev CLI test for this lesson take an additional argument to noted by this one right there we go you need to provide the hash okay so I need to provide the hash there we go all right we’ll do that we’re going to grab that bad boy and I’m going to go like um I’m going to go like that and then I need to grab the is it which hash are we doing that you need to provide the hash of your last commit okay we need to provide the hash of the last commit there we go so I’m going to go back up here I think that’s all I need to technically do d s and then take out this little slash I think that should do everything I need to do there we go got it first try got it so good at this why would you ever need to do that in get you’ll see you don’t technically need to do this in get but it’s really good to understand why this is where the big eye opening moments about to happen for everybody about how git actually works because what we’ve seen so far is that we’ve made one commit right we’ve made one commit and we’re going to call it a and in that commit we have a tree that’s like our root directory and inside that tree we have a blob which happens to be some big long hash and it is contents. MD all right this is very important so this is our Commit This is commit a so now we’re going to add this and we’re going to see how this changes all right all right I believe I did all this all right trees and blobs now that we understand some of our plumbing equipment let’s get into the pipes here’s the terms you need to know tree is a way of storing a directory blob is a way of sorting storing a file so you can see right here I already showed you this there’s the tree we are able to go through through the tree and get all the way to the blob right assignment use get cat file again but this time use it on tree you should see a blob with its own hash use cat file again on this one submit the sees with The Blob hash okay we should already be able to do all this uh because we actually already did this all right let’s find this little bad boy right here where are you where are you where the hell are you there it is hey there we go by bing bada boom able to grab all that stuff out I just grabbed out the file hash cuz I knew what it was or the blob hash all right second uh second command uh reminder of commands get log um and Cat file that’s what we’ve been doing log is a porcelain command where cat file is a plumbing command you’ll use log more often when working with the code uh on coding projects but cat file is useful for understanding gets internals we already kind of talked about that so we’re going to create a second file called titles this is where things get really interesting are you ready for this uh all right so we’re going to go like this titles. MD paste this all in here delete that one uh run through and then we need to save stage and commit the file with the files long as it starts with a B right that’s the thing get uh add this get commit with a B There we go awesome and then run the CLI there we go I’m going to grab the CLI and we’re going to do this bada bing bada boom all right so we’ve created a second commit right this is how you will understand get get stores an entire snapshot of files on a per commit level this was a surprise to me I always assumed each commit Only Stores the changes made in that commit now type one in the chat if that’s what you thought too I assume a lot of you thought the exact same thing that get stored Deltas right yeah I mean look at this a lot a lot of changes in here and I think that’s completely normal anyone that doesn’t think that get stored Deltas right away you’re lying to yourself you’re like yeah I didn’t think that I always knew that it didn’t do that no you didn’t okay your your small brain did not think that we all thought that because that’s totally normal thing to think okay well it’s true that g stores entire snapshots it does have some performance optimization so that your git directory doesn’t be get too unbearably large get compresses and packs files to store them more efficiently get D duplicates files that are the same across commits now you’re probably thinking isn’t that just Delta stores hold on let’s find out let’s just find out okay watch this we’re going to use git cat file and we’re going to find the hash blob of our titles MD okay watch this all right so I’m going to go like this uh I’m going to go uh let’s see I’m going to go get log log one line I’m going to grab this last that’s my last hash right there we go I’m going to go get uh get cat F I know there’s better ways to find your your current hash just shut up this is good enough this is good for people to understand now notice that we have our tree also notice we have our parent now so our parent is our previous commit so we can actually walk back up the tree if we needed to this is if you’re wondering how git log works is that it stores parent pointers as part of the commit all right anyways so we’re going to take our tree and go get CAT file – P this now notice that there’s two blobs okay there’s two blobs here the first blob is the previous contents and this one is now titles okay so I can actually take this and go get CAT uh file- p and I can actually cat out the titles file uh I can actually go to this one and get cat uh G cat uh cat file- p and I can cut out this one and this will give you the contents of that file but notice this right here I want you to look at this would you look at it for a second I’m going to jump into my parent get cat I’m sure I explain this in a moment in the course but I like to explain it this way uh there’s our parent commit I’m going to grab that tree notice that that tree is different than uh is a little bit different like everything’s a little bit different this is the older version of the tree get cat file- P this look at contents look at contents it stores a unique tree per commit but that that doesn’t mean it stores the entire file it just stores a pointer to the file so when I say A commit stores the entire history it stores every reference I know kind of mind blown right that’s why it’s efficient because what happens is you can think of it this way is that let’s say we have Commit a and commit a has the parent tree and then it has the blob that’s pointed to our contents file okay and this is like let’s just say it’s like e f and then a bunch of letters right blah blah blah blah commit B adds that new file and so it’s going to have that same tree but this is going to be a different notice that the hash is different on this tree because this tree has a new set of kids so something has happened to this tree which means that it can even point to trees that have not changed that’s very important so we have a new tree we’re just going to call this one one we’ll call this one two and this one is still pointing to that exact same EF blah blah blah blah but then we have a new one which is going to be our titles which is going to have its uh we’re going to probably need to call this like titles and then it’s going to have its own commit right here and so it doesn’t update this this Remains the Same so it’s very important to understand that all right so let’s see what we have to do here all right we’re going to use cat file we’re going to view the uh the hash of The Blob for our titles and you can do that save that hash somewhere in your notes all right let’s save this hash somewhere in the notes because we have to find it there we go it’s right there I can just come back to that later add a new new directory to your project called quotes inside add two files all right so let’s uh Vim uh what is it you say quotes they say quotes I can’t remember quotes yeah I think so uh what was the first one called uh star wars. MD and then what was the other one uh Dune MD Dune by the way is a great movie Dune Dune can also be fall under the good Sci-Fi um all right so there we go we have those two things stage and commit both files in a single commit with the message C add quotes perfect okay we can do that uh get status you can see it’s right there get add this thing get commit DM put all that in there get log one line should have three commits you can even go like this get log – P which will show the differences so this first one adds this new file uh from nothing to quotes Dune from nothing to quotes Star Wars and then it doesn’t make any other uh edits right and there’s the previous commit which adds titles and the previous commit before that which add contents okay cool awesome we got all those things all right so we did all that one use the command CAD file to view the hash of The Blob for uh titles again you’ll notice that it’s still the same hash correct there you go because the file hasn’t changed run submit this thing Perfect Isn’t that cool Isn’t that cool I think that’s pretty cool I mean I think that’s very very cool for me that was a very mind-blowing moment is to understand how git works because then it no longer felt as confusing and that was my big kind of like I I I I got really really confused for quite some time when I first played around with Git because of that thing all right what does it mean that files uh which were once committed then deleted will be forever kept by git so technically it’s not forever kept by git it’s forever kept by your history unless if you prune your history so you can actually prune your history out of git and so that way it would actually clean up any broken references so it doesn’t actually keep say deleted commits that don’t exist so get prune DF yeah so that will go through so we will actually do that I’ll I believe in this uh in this section we will actually revive a file that was long lost or a commit that was long lost it’s kind of obvious that it’s store snapshot otherwise you need to walk back the tree a lot for files that don’t change often yeah I mean it’s it’s obvious in hindsight but I think the first time you think and you download the first time you ever use a a Version Control you think wow how could it possibly ever store everything it must have to like create the repo by walking all these links that’s why it gets so fast is it doesn’t it keeps your tree and then when you need to change your directory it literally just walks that tree and recreates every single file at each one of those points right that’s but the first time you you wouldn’t understand that right let’s see 100% of the working let’s see 100% of working with Git is checkout Branch ad commit push Force push rebase or merge yes exactly that’s why I say that’s well I mean it’s not 100% it’s like 99 95 there’s log there’s ref log ref log is incredibly important we’re going to go over that there’s also like get checkout so get checkout theirs versus ours it’s very important when you want to be able to just grab an entire change from one side of a merge [Music] conflict let’s take a command apart get config okay so here we go we’re going to actually start talking about config now cu the config is actually useful to use and understand because sometimes you actually want want to be able to change ways in which your G experience changes or in which in which it operates so let’s look at this all right so let’s take a look at the command so get config is obviously the top level it’s still the older style command so instead of get config ad it’s get config D- ad which is kind of a pain in the ass Global is where to store it so it’s either Global or local there’s some other places you can store and get but nobody actually stores things in git right uh or in those ones at least as far as I can tell I don’t know of any use case where you store in system uh I’m sure there is a use case I’ve just never personally ran into it I’ve always just used you know local or Global all right uh so Global stored in uh this right here in your uh home directory get config whereas local is stored inside your git configure right so if I go like this if I go in here and I go uh let’s see uh let’s see what is it LS or find in my git folder what is it name is it config I think it’s config there you go yeah there we go uh cat config it’ll say here’s the things that are inside of your local repository so when it creates a config object it actually takes your globals then it takes your logos and kind of combines them one at a time all right assignment you can actually store uh any old data in your git configuration granted only certain keys are used by git but you can store whatever you want yeah it’s just a key value mapping that’s all it is so you can like uh I know when I was at Netflix we actually had a lot of information stored for how we operated over certain stuff so it just I used to have a bunch of Netflix stuff on my system at one point uh set the following useless key/value pairs in your local git configuration so right here so we’re going to do this for our locals all right so it’s not too hard so you can go like this get config add local so I want to add a key value and I want to do it locally and then what do we want webflix uh CEO okay the prime gen okay uh actually yeah we’ll call the prime gen and then we’ll do uh the CTO as the lanen right that’s the actual CEO of um what’s it called of boot. Dev and then valuation valuation mid it’s a mid it’s a good mid valuation hey who here wouldn’t want a good mid valuation git has a command to view the contents right so if you just go List local it’s going to list everything you can also just cat it out right so as we did earlier you’ll see here’s our top level uh section here’s our keys and values uh so a good thing to notice here is that this is a SE section and this is a key so when you look at this you’ll notice that this is the section this is the key that’s important to know because you can actually delete all configuration by section or by section Keys all right so there you go you can List local so if I just go get config List local it’ll just uh list all my just local only files right here all right so let’s grab this thing jump in here paste it in your company position mid isn’t that everybody’s company position by the way configs were one of the more confusing parts for me not confusing by how they operate because they’re actually exceptionally simple but when I first started using git config was something that I executed once and then I never looked at again and then then whenever I had to touch it I was just like I don’t want to do this right and then I just got all confused by stuff and then I just it felt confusing because I refused to just spend the three minutes it took to understand said it and forget it exactly and then you just don’t know how certain things operate and simply because you didn’t learn this really simple thing this is why I did config because config is one of those extremely useless things you should pretty much never need to know but that one little moment you need to know it it’s very useful it’s very very useful we’ve used list to see all the configuration values but get flag is uh useful for when you’re trying to get a single value right so we can do get uh key remember a key is a section. key name so username webflix CEO there we go so I can we can get the web value so I can go uh get get uh let’s see what is it web webflix webflix valuation and it’ll go and get mid nice right doesn’t get config username just get it uh get config user.name yeah it also gets it you could get must get is the default operation but it’s good to know that because you can also do do set right all right there you go beautiful we did that one uh bada bing bada boom all right this is looking good all right the unset flag is used to remove a configuration value for example get onset key let’s remove the CTO all right so we go like this uh get config unset right everybody you know everybody loves a good unset right I really hate the term unset uh which one are we doing CTO CTO yeah all right I just fired Lane because you know what screw Lane what happened when you tried to unset uh oh try using unset to remove the section I forgot to do that one if you do this what ends up happening key does not contain a section right so you need both a section and a you need both a section and a value or a key name for this thing to be able to be removable when you use unset you have to do unset section if I’m not mistaken I always forget the entire section it failed because you have to use key and value right you have to use both you got to use both duplicates typically a key Value Store like python dictionary you aren’t allowed to have duplicate Keys strangely enough git does not care yes if you look at my git config uh Global uh list Global and then we GP what is it um uh a nit you’ll notice that I have in here three of them okay I had in it default Branch master in it default Branch Main in it default Branch Master yeah it just takes the last one my bad my bad on that one yes you can yes but but if you do that you have to force push right Force pushing is the only way for you to be able to change history for everybody else and if you do that you will ruin the whole repo and everybody will know all right duplicates unset all so unset all is if you want to unset uh entire thing you only need a section then right or sorry unset alls if you want to delete a multi- existing uh key value combo which is kind of odd having an key set combo it’s just kind of weird so if I do this and I go like this and I add a bunch of CEOs I should be able to go in there and go get uh config List local and now you’ll notice we have a whole bunch of CEOs right we have four of them me plus uh Carson Warren and Sarah all right so if I want to undo that I can remove all CEOs by doing unset all right get config unset uh web flick flick flick do CEO there we go CEO has multiple values unset all bada bing bada boom get List local all the CEOs are gone anyways okay so now that we did all this pretty straightforward right pretty straightforward stuff there we go there we go awesome we’re kind of getting through these things uh you know the config SE section it’s it’s it could be boring but whatever it’s fun uh you know it’s you got you just got to learn these things right all right so there you go so we’re going to do the the next thing um which is we to remove an entire section now webflix is a section we have so if we just go remove section we can actually remove all of it so if I go back here and I go um I can add all of this and go get config uh if I go get config List local you’ll see that I have a bunch of webflix stuff so if I go get uh config what is it it’s remove section right it’s not unset section you know how many times I struggle with remove section versus unset and all of that man whenever I’ve had to do anything like that I’ve screwed it all up it’s so easy there you go make sure I really get it out there you know what I’m talking about we want to get it out there and then also you’ll notice that if I go like this cat config uh uh cat get config you’ll notice that it actually removes the section right just fun little fact fun little fact if you’re wondering you know what I mean bless you my goodness yeah thank you yeah you just edit the file directory I personally find that uh I would just rather jump in here and edit this often than doing all that other crap to be real it’s just it’s just much easier CU this other thing is just it’s just really hard you know it’s just really really annoying all right locations uh there’s really only two locations that you should really be concerned about I actually never used a work tree specific location or a system location I’ve really only done Global and local I find location location Lo anyways in my experience 99% of the time you’ll be using Global to set things like your username and email the other 9% of the time you’ll be using local to set Project Specific configuration the last 1% of the time you might need to fuss around with system in work tree configuration but it’s extremely rare yeah I’ve never I’ve never personally had to do it I just know that it’s been done on my system so there you go here’s the set of uh here’s the set of what’s it called ordering so if you have a work tree specific it’s be the most specific therefore that’s going to be the one that gets presented then local then Global then system system is like the it’s kind of like just think about it like uh JavaScript and merging arrays right system is for all users correct global global is not Global it’s not a global list if that makes sense it’s a local Global you know what I mean it’s not a global global it’s a local Global all right suppose you set username to Prime at the system level username Lane at the global level and username TJ at the local level which value will actually get TJ even though TJ does stream but he sucks okay just so you know yeah Global’s the user it really should be it it really should be repo user system for me that seems much easier to understand and TJ catching Strays TJ’s always catching Strays okay shots fed all right let’s see which is stored at the home directory that’d be [Music] Global all right so what is a branch so now we’re going to get on to branching so a get Branch allows you to keep track of different changes separately for example let’s say you have a big web project and you want to experiment with changing the color scheme instead of changing the entire project directly as right now on our Master Branch you can create a new branch called color scheme and work on that branch and when you’re done if you like the changes you can merge color scheme back into the master branch and keep the changes if you don’t like the changes you can simply delete color scheme branch and go back to master so underneath the hood this is what’s actually happening look at this beautiful little little graphic do you like that graphic it’s beautiful huh it’s beautiful does this make sense so here’s a big thing that you need to understand tips just the tips the tips is the commit that is the latest one on whatever Branch you’re looking at okay so you need to know your tips and then eventually they should merge back at some point because that’s how branches work they should be branched off of some uh some they call it the merge base this would be called the merge base we don’t have that as part of this graphic so this is called the merge base or the Le or the uh most common ancestor is one right here and so this is for when you merge it finds this thing right here and then merges things together merge tips use rebates yeah exactly so just so you know these are all commits branches lit like a branch a branch is literally a pointer to a commit that’s it orphaned branches are wild yeah I don’t even know how to create like honestly I don’t even really know how to create an orphan Branch it’s exceptionally difficult to create an orphaned Branch uh it’s just not something you do you know on purpose all right so let’s see because a branch is just a pointer to a commit they are lightweight and cheap this is why when people say branches are really cheap it’s because it’s just a pointer that’s it uh which branch you’re currently running get Branch there we go so I can go like this get branch and you can see I’m currently on Master fantastic remember you should be on Master because we set initial default Branch to master at the start of this course yeah yeah yeah so there we go um fantastic and we’re going to do that and we’re going to execute this thing Bada Bing Bada Boom Confetti feeling good confetti out of my mind all right default Branch we’ve been using GS default Master Branch interesting interestingly GitHub a website where you can remotely store G projects recently changed default Branch to master to main as a general rule I recommend using Maine as your default Branch to work uh if you work primarily with GitHub yeah because if you don’t you have to like go in to every single it’s just a pain in the ass right that’s all it is if you don’t do that you have to actually go into your projects and you have to set it as your whatever other Branch you’re using as the default or else it will use main as the default and then you will get cloned down a repo and then main will be like this empty branch and then you have to undo all of it there you go gitlab has main too and I think newer versions of git has main as default too I’m not sure if G newer versions of git has that as default um like if I go like this uh get let’s see get config remove section um oh don’t do that unset all um let’s see what is it it is a nit uh default a branch there we go and so if I go get config list there we go you’ll notice that I still have this one did I not do this correct am I oh is it lower B oh is it really lower B is it really lower B Branch nah that can’t be right right why why are you still here why por and Maria why are you still here oh it’s cuz I’m not doing gosh I’m so stupid Global globalist there we go I’ve have undid my Global list this is very important to undo your Global list there we go list there you go it’s gone you can see that it’s gone so if I go back here and go like this make dir testy uh testies and CD into testies uh we’ll go in here and we’ll go like this get an it get an IT using Master the name of this initial Branch this is theault Branch name subject to change to configure the initial Branch name do this right here initial Branch name uh names commonly chosen uh instead of master or main trunk Development I’ve seen Dev I like using trunk just to mess with people okay I think it’s funny here get might be old uh get oh it could be old I’m on uh 245 it’s pretty new get uh latest uh version 246 yeah I’m only back I’m only I’m only off by a little bit I used using trunk just to feel something exactly exactly there you go okay so now that we’re here there we go all right so here we go all right how to rename a branch so you go go get Branch uh M for rename right classic M for rename am I right am I right old name new name all right we’re going to set our initial Branch to Main and then we’re going to rename our Branch all right here we go uh let’s just weo back in here and get Branch M Master main get uh config add Global s uh we can actually even do it that by the way you can also do it at a local level so I can go uh nit default default Branch uh what the hell the thing called it’s called main so there we go so I can actually do this at a local level so now only this repo has the default Branch as main whereas all my other ones will still have whatever my Global version is it’s very good to know how to use locals and globals it can be very useful I’ve had to do a lot of things where I have to goof around with different versions all right there we go wasn’t a lowercase B I think the lowercase b was an accident I want to say it was an accident anyways there we go I’m going to copy this one oh my gosh uh okay dang it so it’s gonna my thing requires me to be a globalist I’m now a globalist I am now officially a globalist globalism all right really just Alex jonesing on this thing all right there we go visualizing branches uh throughout the rest of this course we’ll be visualizing branches by the way this is how git does it as well so if you do not know if you go uh man get commit I believe they have it in commit no uh rebase yeah you’ll notice that they effectively do this so I TR I tried to copy a effective version so that way it’s easy to understand easy to see okay sounds good yeah yeah yeah yeah all right let’s see this means a branch called main with three commits a c is the most recent commit as you can see A to B to C Branch there you go so this one right here means a it splits off from a and there’s d and e on something called other branch and B and C on Main so they are diverging branches with the merge base of a all right everyone get that I’m going to be using that term a lot merge base uh answer the questions based on the following diagram which commits are part of Lane’s Branch uh none because he’s a CEO and doesn’t work these days but it’s going to be GH this one bam got it man I’m so good I’m globalist all right there we go all right throughout the rest of this course oh I already answered this one which are part of commits of main uh it’s going to be a b c d got it first try all right VIs izing branches oh we’re doing it again dang we’re going to do primes Branch huh primes branch is EFA or a EF EFA man I didn’t even get close you should already be on the main branch uh your default branch and you can always check with get Branch I wonder if there’s a way to name your default Branch something that would break your system can you do rmrf uh see two ways to create a branch right get Branch New Branch name this creates a branch called New Branch uh the thing is I rarely use this uh command yeah I rarely use this command reason being is that whenever I create a branch I also want to switch to that Branch right right so I typically use get checkout B just because that I mean I’m I I guess I am a boomer it’s hard for me to break that habit but the newer ones is get switch C so I’m trying to show you kids you youngans to use get switch C all right that’s the one you want to do all right I’m just so used to get checkout B I can’t help it so if I use get checkout B sorry I’m old my fossils are creaking you get the idea okay so what this does by the way whenever you create a branch it takes your current location and that’s where it points to all right so when I do this my new branch that will actually create a new loc it’ll create it’ll have the exact same sha or the exact same uh commit yeah it’s your head location so it’s it’s good to know that because a lot of that’s kind of like one of those confusing jumps people have to make oh yeah on itchy there you go all right anyway here we go uh create and switch one called ad classic so let’s just do that right now there we go I’ve created ad Classics uh let’s see and then let’s see run get Branch to verify so I can go get branch and you can see that I’m on ad Classics get that and if I go get log you’ll see that I have ab and c and if I go get log uh main you’ll see a b and c the same thing they’re the same thing I believe if I even go like this uh find uh get what is it uh grep refs something like that right you can actually see this right here so you can see it right here so if I go right here and I go uh cat that you’ll see it’s pointed to this thing and if I cat uh main it’s poed to the same thing there you go makes life easy for you to know these things learning gets sucked yeah learning get well it doesn’t it’s just it’s just time cons it’s a bunch of little things that you just have to learn all right switching branches uh we talked about using get switch to change branches there’s another command you’ll certainly run into and it’s been around for a long time and older developers use it get checkout okay calling us older developers hurts a little bit me in the past me in the past get switch is a newer command that is meant to be more intuitive and user friendly uh it probably is more user friendly because get checkout is kind of like this grab bag because you can also like check out sides of a merge conflict there’s a lot of weird stuff shows the history get okay get developers of a certain generation and that’s me also uh it’s recommended to use get switch over get checkout for simply switching branches that’s what they say let’s okay let’s switch to a branch called Prime all right there we go uh the new way the old way right there you go for this course we’ll stick with get switch right there we go all right switch to Branch main run get branch make sure we’re on there switch back to Classics run this one run this okay I’m not going to do that yo dog uh I’m happy for you or congratulations or I’m sorry there we go we passed I’m not going to switch around but you get the idea it’s just get switched without the- C for create that’s all all right upleveling our abilities will uh use the ad Classics Branch to add a commit to the project without affecting the main branch so we’re going to actually create the D here in other words ad Classics Branch will have all the commits from Main plus a new one all right so we’re going to switch to add Classics we’re going to create a new file called Classics CSV and there we go so I’m going to go uh Vim classics. CSV uh go here I’m going to yank that bad boy paste it in here of course the classics uh you know The Princess Bride I actually watch this every Christmas it’s literally the greatest movie of all time here we go all right so we have this we’re going to stage and commit the file the commit message to start with D all right run commit okay here we go so we’re going to do that one get add this get commit Dash D is great there we go and you should be able to see the commits with the branch with get log we don’t need to do that let’s copy that bad boy paste it in make it happen B bam bam bam got it we’re all in the good stuff so let’s go over here so we’re about ready to start get into some good stuff log flags as you know get log uh shows the history of your uh commits in your repo there are a few Flags you’d like to know short full no I like to I don’t really use decorate decorate typically works well uh if you want to see where things are coming from so you can do get log uh decorate full if you want to see a bunch stuff on Line’s the one I use a lot okay this is the one I always use because if I go get log you get like all this crap but if I go get log on line you get that that just feels nicer right that’s the one I want what the hell is decorate well this is decorated right now and the reason why it’s decorated if I’m not mistaken if I go uh no pager no pager uh no okay there we go all right it’s not doing it effectively decorate it decorates default default version I thought I thought there’s a way what’s the way hold on let me go like this on line uh T out there you go so there you go that that took it off so if you pipe it to another program this is kind like a non-decorated one a decorated one right here shows where you’re pointing at so head which is also pointing to add Classics main is on C that’s what decorate does so get log decorate equals no will not tell you anything about where stuff is at does that make sense and then you can also use git log remember how I talked about graph graph is pretty cool graph uh one line so you can kind of see that I’m just going it’s just all one line right now there’s no there’s no change right now but we’ll get to the point where we start seeing some changes don’t worry we’ll see it we’ll see it uh there we go fantastic I think that’s all I need to do run get log with full decoration we already did all that explain the decorations let’s go we got it we got the confetti we’re confetti out of our mind I’m level seven by the way you guys won’t even understand what it’s like get propaganda hour absolutely uh Kung Fu no get Fu remember git stores all the information in files in the git subdirectory at the roof Ro of your project even information about branches the heads or tips of the branches are stored in get rep’s heads if you c one of the files in that directory it should be able to see the commit that the hashes points to which we already did use find and Cat to find the commit hash of your main branch we already did that one uh what is stored in get ref’s head uh one file each for a commit oh what is in there I forget let’s see it is going to be get ref’s heads is going to be each one of the branch names one file for each branch containing the commit hash of that Branch points that one let’s go let’s go I’m a genius nope we’re not going to watch this branching and get is practically free and it really is kind of the core operation when using git but at some point you have to get that work from a branch back into the main line and this is where merging comes into play now a typical workflow for pretty much every Dev looks like this first we need to update our repository to the latest code this is typically done through get fetch or get we’ll cover those more later you Branch off the main branch and give it a name that kind of represents what you’re working on new feature a you fix the bug create the feature update the docks and create your one or more commits on that Branch then finally you merge those changes back from your branch into the main line typically when you’re at a company this will involve some sort of poll request on GitHub on stash on gitlab but conceptually it’s no different than executing git merge on the command line oh what’s the point of having multiple branches you might ask they’re most often used to safely make changes without affecting your or your team’s primary Branch however once you’re happy with your changes you’ll want to merge them back into your main branch so that they make their way into the final product all right so here’s the visual look at this beautiful thing and then notice this this right here is called a merge commit it’s very important to understand merge commits because if you don’t you don’t understand why rebase is good so merge commit and especially when you look at a log we’ll look at the log here shortly but it will actually show you why uh or how these things kind of exist and why they’re unique and why it allows for log graph to be very nice uh so hold on let’s see what the assignment is just to make sure I don’t get ahead of myself uh first switch back to main next our contents file is eerily empty yep update uh update it to contain this all right there we go now the yep and then we’ll this okay perfect perfect let’s go all right so what we’re going to do is I’m going to go like this we’re going to get check out main oh wait no wait get get switch add Classics get switch main don’t use checkout we don’t use checkout we’re not using check it out we’re not doing it all right and then update this file right here don’t you do it uh get status it’s nice it’s not it’s not mgit all right there we go so commit uh let’s see commit the changes with a message starting with e all right so let’s commit these changes get add this get commit uh e uh let’s see uh contents such contents with a new line at the end why I don’t know why there we go so now we have this one we have ABC uh abc e abc e and ABCD awesome so we should be able to do the whole get log graph all look at this nice bad boy look at that look at how graph does that it’s nicer in one it’s it’s nicer in one line honestly one line you can see right here so there’s ad Classics it’s been branched off at that point and here’s this guy so it’s a nice way to look at all your stuff there you go why not use checkout it’s just older switch is the one right all right there we go fantastic right so I should be able to just do that everything should be good there we go confetti it out of my mind all right merge commence we are merging two branches together with diverging history look at this thing right here the diverging history simply means that main branch the one we branched off of at Point a has commits and we some branch have added more commits main has B andc our Branch some branch has DNA that means when we merge we need to be able to create a new commit that represents these two diverging histories as one this is called a merge commit and it’s the only commit with two parents the process for a merge commit looks like this first we need to find the merge base the merge base also called the best common ancestor is the nearest ancestor that is in common to both branches and in this case that would be a we then play main Branch’s commits into a new commit and then we play some Branch into that same commit when all the changes are in that new commit we commit it to Main and in this case we call it f and we give it two parents one parent pointing to C from the main branch and the other parent pointing to E from some Branch if you use G log you will actually be able to see the diverging from a the two diverging commits and then the coming back together in F merge commands are the result of just merging two things together yeah so what a merge commit does or how a merge works is that when you merge in something it takes it finds the most common ancestor or the merge base then it merges Main and this one together to make one Super One make one super commit adds that to the front of the branch that you’re on and then has two parents which is where you came from does that make sense so if we were to merge Vim Chads only in main while using this we would find the merge base or the best common ancestor uh in this case a replays those two commits bam creates a special commit called a merge commit and then this thing has two parents there you go fantastic right uh so in our current webflix history we have this we have main abc e and we have ad Classics which is D so when we merge we should have this like we should have an F commit that’s going to be this little merge Branch right here so let’s just do that now get merge ad Classics I assume that’s what we’re supposed to do and we wanted to go f so that way we can denote it there we go we’re going to write that and we just did it perfect right so now if I do this whole on line decorate graph parents business hell yeah that’s a lot of stuff you can see right here classics branched and then came back together and you can see right here that this is a merged base because it has two parents or not a merged base sorry uh why would I say merch base it’s not a it’s a merge commit because it has two parents never worked with two parents children yeah most children in get do not have two parents this one does so there you go this you can actually watch it because this one points to this Commit This one points to that commit they both point to the same merge base there you go now that everybody knows feels good right a lot of arch users out there confused about merge commits all right so logging has to be one of the best tools in the git belt because git has extensive logging and observability if you need to recover work visually understand how you got to this point commits along the way messages that you have created where the branches and tags are including in your repository your remote repository and of course all the tags that you currently have and much more than logging has it let’s break down a Quick Command right here get log on line graph decorate parents now this looks like a lot of options but actually it’ll make a lot of sense once you understand what those options mean one line will give you a condensed view of your history first off the hashes are shortened to seven characters which is the minimum amount get requires for you to specify hash also you get the commit message this gives you a nice quick view so you can can see what happened in the past graph will draw all the little lines so you can see exactly how your commits have diverged and come back together through merges decorate will give you the branch and tag information this can be nice to see how far you’ve straighted away from a branch or where a previous Branch might be parents will give you the parent commit upon every other commit this can be very nice for merge commits because you can see where the two parents came from to create the merge commit go ahead give it a try yourself oh we already did this I already kind of explained this beautiful niceness right here uh each Aster represents uh a commit in the repository we actually already talked about all this this is fantastic why does the first uh line show three commit hashes uh because it’s the first commit in the history no because it’s a merge commit with three parent commits no because it’s a merge commit it shows its own hash and the hash of both of its parents we already talked about that I think that makes sense right wait where did where did my log go oh I didn’t print out the log there you go you can see these are the commits right here these are the lines this is its sha and then its parent Sha see that’s parent parent parent parent it’s commit Shaw parent that’s its commit Shaw this is its parent it’s the parent or the shaw it’s parent the shaw this is Batman right here no parents beautiful asky beautiful asky there we go all right merge logs let’s see you can output your get log decorate graph parents aside from the hashes look something like this we already taled well we already did this we just got to answer new questions why is the weird diagram EG all these things uh whoopsies I I didn’t mean to click that it’s what happens to your brain on Arch Linux after 10 years that’s not what I wanted to do um it demonstrates the branching structure three commits were merged into the main no it demonstrates adding Classics was merged into main boom that’s what it demonstrates it’s beautiful I want to make sure you guys get it all right a fast forward merge does everybody who knows what a fast forward merge is I’m curious type zero if you don’t know what it is I’m actually curious about this well lot of zeros dang dang that’s a lot of zeros a bit I’m shook I’m shooking right now okay the simplest type of uh merge is a fast forward merge let’s say we start with this one main branch and then delete vs code now we run this on Main get merge delete vs code because delete vs code has all the commits that Maine has get automatically fast forward merges in other words the best way the branch you are merging onto if the tip of that branch is the merge base then you can fast forward merge does that make sense yes in other words I tried to one more time I tried to that’s why I’ve been trying to say the word merge base remember a merge base so for these two commits right here a mer the merge base is this right here so in this example this one uh this one was main this one was add Classics so the merge base was this right here so if Classics was branched off instead of such contents the merge base is the tip of the branch you are merging on therefore you there’s no Branch right it can just literally update the pointer the end kind of sounds like rebasing main no it doesn’t sound like rebasing main that’s not what rebasing does we’ll explain what rebasing does in a moment rebasing has nothing to do with merge people sometimes goof that up a little bit it’s not what it does um all right because delete vs code has all the commits main has get automatically does a fast forward merge it just moves the pointer of the Basse Branch to the tip of the feature Branch that’s all it does bada bing bada boom all right uh we’ll get to mer we’ll get to rebase here shortly so you’re just adjusting head pointers that’s pretty much what you’re doing so when you’re doing a a fast forward merge you just main just now points up one right assignment uh because ad Classics branch has been merged into main we don’t need anymore delete that Branch okay we’ll delete it uh create a new Branch off of Main update titles uh let’s see add a commit to that branch that updates titles MD file and add Curious Case of Benjamin Button as the final entry in the list and then use G okay we got to do a couple things here hold on hold on let’s delete get a check not checkout switch de see I I always mess that one update uh titles titels uh there we go uh let’s just open this up and go add classic contents what we doing titles uh Curious case for Benjamin Button is that the one we’re doing titles MD we’re going to add The Curious Case of Benjamin Button there we go we’ve added it so now we have that and then we’re going to just create a commit with G all right get add this get commit dasg a curious case all right there we go uh run one line to see what we’ve done here get log one line you can see right here here is update titles here’s main Main’s one behind you’ll notice that this would be the merge base right so Main is currently if I were to merge this onto main main would also be the merge base and that’s very very important to know all right so let’s go in here let’s do one of these there we go does all this updating bada bing bada boom looking good looking good confetti let’s go all right so fast forward so now what we’re going to do is we have this diagram and now all we need to do is just merge it back on so we’re going to switch to Main and we’re going to merge update titles onto it and you’ll see what happens here so get check out main sorry I did check out not switch get log uh you’ll see that I don’t have G on here if I go on line it’s probably easier to see no G if I go all you’ll see that g does exist only in update titles there we go and then we can go like this graph and you’ll see right here that g is on the end so it’s just straight ahead so now if I just simply merge get merge uh update titles you’ll notice that it does a fastforward merge and now notice if I go like this get log one line notice that this one had a branching Factor this one does not there’s no Branch there’s no merge commit uh and you can see by me going like this get um uh parents so you’ll notice that this one is a merge commit because it’s merging e44 and 7 a0 this one is not because it’s just having its parent to be one behind very important to know okay that’s a very important thing to know people just you know they just don’t know these things all right there we go I hopefully I did everything correct and I didn’t accidentally go forward sometimes I go forward too fast and screw everything up all right so now we’re going to go to rebase everybody thinks rebase is the most awful thing ever and it’s on Twitter if I go to Twitter I guarantee you I search up the word get rebase and there’s going to be something awful up at the top get rebase or hopefully it’s going to be me saying people don’t understand it all right mer all right here we go there you go look at that see open Slack someone help with rebase branch in Flames sends thoughts and prayers close the slack go to gym rebase Force push I up I get rebase like look at this it’s just it’s an endless supply Hacker News is having a get rebase discourse again I like this Comon a lot see it uh blot the blah blah blah blah blah blah blah blah blah blah again they hate this one I think this is the way okay personal opinion rebase is tight rebase is the only way to do it something about get rebase thanks yall for coming I don’t even get this one okay I don’t even get this one this one must be get rebase this is get rebase so you got to be careful when you’re rebasing okay you could screw up the world I just want you to know that okay you could screw up the world rebase might just be one of the most misunderstood features of git where the fear typically kind of comes from is that somebody changes the history of a public branch and when I say public Branch I mean a lot of people rely on this Branch for their repos as well and of course when they pull and the changes have been somehow altered in the past all these conflicts and these weird git errors start happening and it just causes a disaster for everybody and then everyone says rebase is terrible I will never use that only use merge well skill issues you used it wrong to understand rebase you simply need to understand its primary use case rebase helps you to take the diverging commits from one branch and move them to the tip of the base branch that the feature branch is based on now that sounds like a mouthful but it’s actually pretty simple so take this graph right here we have two branches Main and Feature Feature branches from Main at commit a and Main gets B and C added to it while the feature branch has d and e now we want to be able to take the feature branch and get those changes from Main now with your current knowledge you would probably merge main into feature creating a merge commit and that does have consequences and we’ll discuss more about that in part two but for now let’s focus on rebase rebase is is going to allow you to move forward feature Branch from diverging at Point a up to diverging off of Point C allowing for a fast forward merge if you wish to get it back into Maine this also allows you to maintain a merge commit free history and again there are some consequences for that and they can be quite nice and that is it you’ll notice this gives you the opportunity to do a fastforward merge and kind of have a free of merge commit history this will allow for some Advanced G features to be more easily usable if you maintain this type of workflow okay so rebase is very very simple all rebase does is update where your branch points to this is well okay I mean technically there’s actually a couple different use cases for rebase but let’s just start here this is the first one so pretend we had Main and we had feature Branch if we were to get rebase main on our feature Branch it would take the pointer which is which it’s parent pointer it’s its merge uh base is pointing at a and it’s going to go all the way to C then replay your commits d and e and now you have a linear history which means you can do a fastforward merge okay so it’s actually really really simple and you’ll notice that DNE even though the commit message is the same you will now get new commit Shaws why would you get a new commit Shaw well that’s because D its parent is no longer a it’s C so therefore D has a new sha e has a new sha because D has a new sha now you have to fix all the conflicts if there was a conflict while rebasing there would be a conflict while merging if you’re if you’re experiencing continual conflicts it’s because you don’t know what you’re doing and I will explain why in a little bit okay okay buddy can you calm down again whenever I see some whenever I see somebody say something about all these conflicts and all this stuff with uh with rebase what it makes me realize is you don’t know what rebase does and how to and how to get around stuff so it just moves the merge base exactly it just moves the merge base and that’s really important do you talk about conflicts and G two yes so git one is all about using git for yourself get two is all about using it for a team so it takes the code from d and e and applies them to uh code version C yes so literally so the exact operations of get mer rebase does this so let’s say we’re on feature branch and we say get rebase uh main what happens is that we check out main I’ll call that the target Branch we check out Target Branch we then take Source branch and apply its commits to the tip of Target Branch then we update Source Branch to point to the new uh to the new tip why is it uh important to change basis uh reverting so people really hate get revert it does make things better when you need need to revert so reverts typically happen in larger companies if you’re just working with like two or three people you’re probably never going to revert anything and that’s fine but if you have say a 100 people working on the same repo and there is a test that needs to go out that day and you accidentally screw up Main and you need to unscrew up Main and they can’t wait for you to go okay this is going to take me a couple days to fix you have to revert your commit out of the history and then you have to re-release into production the reason that’s nice if you properly do what I consider the best way to use git which is to always rebase right so here’s ABC you always rebase such that you can do Fast Forward merges and whenever you do this you uh you take this and you merge it into a singular commit right you squash it is what’s that called is that if you run into a situation where you need to use revert or revert I always I never know how to I never know how to say the word revert in that kind of tense uh or in that kind of sense I always call it revert I never I don’t know what to do here anyways when you do this it then is really easy to remove this right always rebase in local branch I rebase in public okay that’s crazy don’t rebase in public you can also fast forward merge too yeah just do it with idea that’s not a good way to do things I’m just throwing it out there knowing how git works and setting it up so that it can be very easy to change things but uh but but sometimes I just commit a just a lot of commits you should you should commit early and often okay this is a good way to do things committing early and often is great do that but do you lose commit history when squashing it depends you loose your history of your local changes and that’s okay you can do that you can squash them down to a single one so that way when you merge back into the main branch the public Branch it’s just one commit now maybe you want those in two commits if you want them in two commits then squash the commits into the two ones that you want maybe you want them in all the commits then keep them all right you can kind of choose what you want to do cuz when you revert you can do the same thing as you do in cherry pick and provide a list of Shaws to like take out or put back in uh get rebase interactive is the best thing that is get rebase interactive is very very nice and we’ll do that for when we’re squashing right why would you go with interactive rebase and squash your commits into a single one instead of uh merging with a squash uh I do that that’s how I do it so locally whenever I’m about to do anything I get all my commits prepared I rebase I squash and I push things up try making yes we can do this too uh this is one good way to do things but we’re going to get to that that’s later on right I’m not trying to we’re trying to stay on task here okay lot of questions rebase is always a lot of questions because rebase gets the biggest bad RP from the internet and most people have absolutely no gosh dang idea what rebase does and so then they’re like oh but rebase is bad because it’ll screw up your history and you’re like you’re right you can you can f yourself up with rebase absolutely you can chop off your finger with a skill saw it doesn’t mean skill saws are bad it just means you should probably know how to use a skill saw before you just start slanging that blade all around right I know that’s crazy both rebase and merge can be used to integrate changes from one branch into another in some sense yes very very true anyways all right rebase versus merge BL blah blah blah we’re going to do this one uh blank can add additional uh commit and blank does not rebase merge can add an additional commit rebase does not correct so if I’m rebasing and there’s never conflicts can I still lose history for months go so I’m not sure what you mean by losing history people say that cuz they don’t know what it means what are you attempting to say if you have history that’s in a public Branch you will not change it unless if you interactively squash rebase and then Force push which if you do that you’re a bad person you should be fired that’s crazy don’t ever do that you will you will actually ruin everybody’s life you actually will yes conflicts happen whether if there’s a conflict while rebasing there’s a conflict while merging that’s a good good thing to understand nobody wants to see million see see your millions of commits just squash it yeah a lot of people prefer the squash all right we need a new Branch uh feature branch and to be able to practice our rebase we want to not include some of the commits in recent main uh we’re going to use get switch command and create and switch to a new local branch called update Dune but Branch off the decommit you can supply a commit hash directly and get switch so we’re going to do this right here we’re going to get switch Branch it off of Dune okay people so we’re going to go like this get log uh on line and there we go so D is that bad boy right here get uh switch dasc update Dune and from that one there we go I said update done you get the idea so if I do that another little oneliner right here we’re going to see this beautiful part right here if we do on line all you’ll see that head is pointed right here update Dune I’m close enough it’s not my fault I didn’t copy pasta what can you do okay so now that you see that this is good this is good good good good good stuff there we go we’re going to paste that in we should be wait what oh update okay it’s actually requiring me to do that get Branch M up uh update uh done to update Dune I don’t know why you got to be like that get boot Dev okay you can’t let a man have oopsy daisies here so you never push until your feature is done or you need the force push yeah I I don’t I don’t I don’t push my features up regularly I keep them and I commit them and I get everything I want and then I push it up and then there’s some there is some there is some a little bit of style points here of how you want to handle things after that some people don’t like to make changes uh some people don’t like to make changes in the sense of having to force push again so all PR changes will become their own um commits and then squash that one more time and then merge it when it’s ready that’s one way or you can merge your PR changes back into a single commit and and then you have to force push it so it’s kind of like you got to Riz get your own way and some people prefer the you know the the pr changes to be their own separate commits some people don’t that’s the rizing part you know also if you have really shitty cicd pipelines you may find yourself constantly you know doing that and get Force push every five minutes with amending draft commit yeah that’s me called using get we’ve all seen that we’ve all seen it where it’s just a wall of test test test test test test test test test test test test test test test it’s just the worst yeah I get a bad feeling when not pushing for several days okay I I mean that’s fine you can have of either no one’s telling you not to it happens it is kind of weird right I feel bad not pulling I like to pull pretty regularly all right so now we’re going to rebase main this will do the following check out main remember I called that Target Branch replay one commit at a time from J diesel onto Main update J diesel Branch support to the latest commit the rebase does not affect Maine while J diesel has all of its uh had all the changes from Main there you go so it’s going to pull in those changes so our assignment let’s add two commits to Dune Branch add the following quotes to Dune the spice must flow and then for that will be H and this mind killer all right let’s do this okay Dune is a really good movie okay I don’t care what you guys say all right wait spice must flow okay good uh get status so you can see that get add this get add this get commit Dash I think it’s h uh spice me daddy why not uh go into here that was H we’re going to do I grab that one go back in here do that save that add get commit fear me Daddy I think so I think that’s right I think we just got it okay so I should be able to get log and see this thing so there we go you can see that right here in fact I can go like this graph would make it nicer so you can see right now that I’ve branched off of D you can see my little Branch off of d right here that goes up and does uh does this right here H and I there it is right so you can see the branch right here this is the main line This is the uh the new line that we’re doing what is dash all it it lists every last Branch right so if you to list every last Branch you can I believe you can also forgive me if I get this wrong I believe I can also go Main and update Dune right you can also specify which branches you would like to see how they do what is happening with that here let’s take a look at that so you’ll notice right here if you remember this right here was when we did our merge B our our merging and all that fun stuff right so this has update titles and Main pointing right here do I need to I don’t think I deleted update titles did I did I forget to delete update titles get Branch delete update titles are you sure you want to delete it Force get the hell out of here all right all right there we go so you can kind of watch this thing move right so there there was remember we had a split at one point right here that had DNE so this is the merge commit from DNE so if I go here I forgot to do parents this will make it more clear so you can see right here this is the merge commit for from uh which one is that one from E and D that’s the one we created earlier this right here is our current One update Dune so you can kind of see each one of the lines forming and we split off uh we split off on D right here so the split went up this way to H and I so it goes i h d CBA a for update Dune and for main line is going to be GF e D or is that or actually it’s going to be gfd e CBA I believe that’s how that that’s the ordering there you go that’s that’s how you read it you read it from top to bottom left to right classic real real classic right there all right Perfect all right we’re going to do those two things we have those ones we’re going to run one line I like mine where I did run line main you can see here’s a more graphical depiction of it all right you can see that so now our goal here is to rebase it and so we’re going to have uh does it tell us to rebase it I can’t tell finally while still on that we want to rebase or change it so when we rebase them you’ll notice right now here let’s go back to this thing you’ll notice that we Branch off of D for I and H so when I go like this get rebase Main and reexecute this you’ll notice it got a lot more simple we are now right here it’s now branched off of G which makes it into a nice linear history all right we just moved our Branch forward you’ll also notice oh I I didn’t I didn’t save the output or else you’d see that the the stuff all changed there you go pretty straightforward right there you go no conflicts why would there be a conflict we edited different files so remember conflicts will happen universally since we do not have a conflict in a merge we’re not going to have it in the rebase pretty much either uh there might be some Edge case where that’s not true but I can’t think of why that would ever be true because a conflict in its core happens because git has three operations add delete modify and so if two operations modify the same line it can’t do it it doesn’t know how to merge those two things because git operates on a line by line basis it does not operate within code because once you operate within code it has to understand the intent of code and therefore it can’t so therefore it’s going to say hey since I can’t understand the intent of code you’ve modified the same line you need to do something about it I don’t know how to do something about this does that make sense all right the advantage of merge is that it preserves the true history of the project this is true you know where all the branches happened and where all the merge commits happened it it shows when branches were merged and where one disadvantage that it can create a lot of merge commits which can make history harder to read and understand which can also make it harder to manipulate history with uh reverts and reverts can be a strategy especially in bigger companies I had the revert at Netflix probably 10 times in my life right it’s real I’ve had to do it comments can cause conflicts I’ve don’t know about oh comments as in comments and code yes comments and code yes a linear history is generally easier to read understand and work with some teams enforce the usage of one uh of one or the other on their main branch but generally speaking you’ll be able to do whatever you want with your own branches it’s true how painful was it not painful at all uh when it came to that because I always did I always did the same stuff I never merge committed I always did all my stuff really nice and made sure I had a single commit so whenever I had to revert which did happen uh all I did was just revert commit revert commit walked away right easy easy peasy right warning you should never rebase a public Branch like Maine if you do this you will destroy your life and what I mean by that is when someone pulls it will say your histories are out of sync and then you’ll have this huge conflict problem and then you have to effectively undo everything uh it’s generally good maners to rebase a public Branch onto your own personal branch all right hold on rebase a public Branch onto your personal Branch that’s kind of a confusing question I think what it’s saying is rebase a public branch and change its history if that’s the case no that’s bad there you go rebase and get merge are different tools all right we already talked about this it’s generally okay to merge changes into your own uh private Branch or to rebase your branch on top of a public Branch yes this is [Music] correct all right undoing changes one of the major benefits of git is the ability to undo changes there are a lot of different ways to do this but first we’ll start by going back a commit history without uh without discarding changes all right we have a little story you guys ready for a little bit of a story I don’t even merge I just pull damn it’s crazy why would you do that let’s see okay the new internet webflix tried to add his favorite movie to the titles file but overwrite the entire file by mistake to simulate that on update Dune Branch go ahead and overwrite titles with just one line The Internship oh Vince Von oh Vince vaugh all right I don’t know why that happened I think that’s what they’re looking for oh he actually doesn’t even want that he want the entire file overed there we go that’s what that means if you’re wondering this just means redirect output but it redirects output and destroys the file double carot redirects output and appends to the files all right make sure the file is changed by running get status and then commit with-j all right uh get add this get commit J interns am I right there we go fantastic am I right am I right am I right all right get reset is a command that can be used to undo the last commits or any changes in the index by the way I use reset quite a bit okay not just soft either also hard but soft actually soft reset is an amazing thing to use and it becomes exceptionally good when you screw up a revert cherry pick or a rebase and so it becomes really good the get reset soft I know some of you some of you prefer hard but hard isn’t always good okay it’s not it’s you can’t go hard all the time you got to go soft sometimes trust me on this one I’ll show you all right get reset command can be used to undo the last commits or any changes into the uh to the index staged but not committed changes and the work tree unstaged and not committed changes so we can do re get reset commit hash or it it really shouldn’t be commit hash here this is kind of a oopsy daisies it should be committes commit is a term used by get to say something that looks like a commit so it’s some sort of hash or something that can be calculated into a hash right uh the D- soft option is useful if you want to go back a previous commit but keep all of your changes committed changes will be uncommitted and staged while uncommitted changes will remain un are staged or unstaged as before so our current branch is right here it should be a commit J now we should be able to go to commit I um by doing a soft reset so I can go like this uh get reset soft now normally it’s said to go uh in here and go get log one line and go and grab I and do this right here and go and get reset I you don’t have to do that you can also go if it’s directly in history you can go get reset soft and go head which is where I’m pointing to and then the amount of steps you want to go back so I want to go head one back so that’s going to be to I there we go we did a reset soft that if I go like this get status you’ll see that I have the titles get diff uh staged you’ll see that I’ve deleted everything for internship uh get diff you can see there’s no changes uh no uncommitted changes to the work tree and if I go get log one line-1 you’ll see that I am currently on I pretty cool right so I just did I undid those changes while maintaining the changes available if you don’t see why this is useful in rebase I’ll show you later okay don’t worry we’ll show you we’ll show you yeah it’s good huh I like it I mean I personally like that there we go uh J should be gone for the commit log there we go we should run this thing yes uh yeah git log uh G log uh get oh my goodness I showed this earlier git log p on line is is really nice too uh on line-1 cuz it’ll show you the previous changes so you can see fear’s the mind killer that was definitely I you can see that right there I’m more of a mixed kind of guy okay okay interesting interesting I can’t really argue that can you just keep oh dang I was hoping I could get more I was hoping I could get more uh get add- P do you use this no I never do I never do patch stuff I never do any of that interactive adding honestly it’s that so this right here I would definitely use with an editor it’s way way nicer um I’ve never used I’ve never used uh that no I’ve never used that yeah if you’re going to do patch adding so uh get or um uh man get add uh dasp right this is interactively choose Hun’s the patch so hunk I don’t know how they determine the size of a hunk uh but hunks uh is just like somewhat of a change so long as there’s enough lines between two changes it goes uh here you go here’s hunk one here’s hunk two and therefore you can actually say I want to add this one but remove that one but if we do it with interactive it actually makes it a lot easier here I’ll do it really quickly okay I’m going to do it really quickly okay there we go uh let’s just there we go that’s good enough uh let’s bring it right up into the middle I’m going to just go in here we’re going to go in here I I know I’m screwing things up who cares uh’s let’s just go like this remove me right there we go I’m going to remove me so now when I go in here I can actually go like this I’m going to add one up to the top and one to the bottom and when I go in here you’ll notice that there’s two hunks those are hunks right there so if I were to go uh get add uh that- P you’ll notice it’s like hey do you want to Stage this particular hunk no I’d much rather personally go in here and go like this and so I can go I want to Stage that one and I want to remove this one now I only have one change it’s much easier to use a graphical editor for that stuff split is useful split is useful yeah so anyways all right let me just undo that one uh and then go in here and go get reset uh soft so now here’s a problem here’s a problem everybody I goofed up right now I have this commit that isn’t quite right and all that I bet we could find the other commit couldn’t we oh we could but we’re not going to we’re not going to uh get status there we go get diff uh stage there you go you can see all the stuff I’ve added to it that’s fine all right so get uh hard will undo everything so get hard will not only undo the changes and move your branch back it will also clear out your index and your working tree assignment get run status to confirm this one uh run get reset hard to undo the changes don’t move on before you’ve done this okay there we go so I can go like this get reset hard uh cat titles this now you’ll notice everything’s good there we go so I did a reset hard which will change which will undo the index and the working tree so like changes that are unstaged so that is not no because un well unstage yes it does unstage so it just depends so watch this so if I go like this uh let’s go like this I’m gonna add a line right get status this is an unstaged change to the working tree get reset hard get status it’s gone very important but so if I uh get back here but if I CLI this Foo and I say Foo get status this is an untracked change very very important so when I get reset hard get status you’ll notice that the untracked change because it hasn’t added my working tree yet this is an unknown file it does not get reset hard important to understand that okay important to understand those things there we go we did all that let’s grab that let’s paste that in untrack get so fun with get ignore it can be very annoying with get ignore yes uh there we go danger I want to stress how dangerous this commit or this command can be if you were to simply delete a committed file it would be trivially easy to recover because of the uh it is tracked in get however if you use get reset hard to undo committing that file it would uh it would be deleted for good yes you can delete by accident forever so if you have a change that you never committed you have an unstaged change hanging out and you do a get reset hard you can lose all of it very important to be careful about that so be careful about doing that okay be careful reset to a specific commit if you want to reset back to a specific commit you can use get reset hard command to provide that and you have to provide a hash this will reset your working uh directory and index to the state of that commit and all changes made after that are lost okay so this is this isn’t technically true uh I don’t this must have escaped my eyeballs but they’re not technically lost forever you can still recover them via uh ref log or by looking at uh you can you can peruse through a lot of the G stuff and you can cherry pick back in this is true but it can be a bit of a pain in the ass to do that right again be super careful in part two of the course we’ll cover more advanced stuff uh ref log has saved me many times it should ref log is very very good get reset hard blank undoes the commit changes delete uh deleting the changes forever unfortunately that is not sure I’m not sure how that escape me it perceiving deletes them forever it removes the changes from your branch and moves your branch head so it appears that they never existed you can still get them right anyways I want to stress oh let’s see hold on when provided a hash get reset hard blank moves your current Branch back to an older commit and destructively discards uncommitted changes correct there you [Music] go all right get remote uh often our FR ofies read co-workers make code changes that we need to begrudgingly accept into our pristine bug free repos this is where distrib uh distributed in the distributed Version Control System comes from we can have remotes which are just external repos which mostly the same get repo history as our local one all right that’s the nice part it’s a distributed Version Control System right you get you get the idea uh when it comes to git the CLI tool there really isn’t a central repo GitHub is just someone else’s repo only by convention and convenience have we as developers started to use GitHub as a source of Truth for our code so GitHub is just is just another version of your repo and that’s very important connection to make because if you don’t you might find yourself fairly confused by a lot of stuff let’s create a second repo called webflix local and let’s see as a sibling directory to our original webflix so we’ll do a little CD blah blah blah blah so I’m going to go make derb back webflix uh webflix local there we go all right let’s see run and submit the CI test from inside this one oh we need to get AIT to create a new empty repo all right uh let’s go like this let’s CD back back webflix local get AIT jump in here jump over here paste that in all right we’re moving we’re moving fast adding a remote and get another repos called a remote the standard convention is that when you’re treating the remote as the authoritative source of Truth such as GitHub you would name it origin there’s also some like basic rules around origin that can be applied there’s some convenience defaults and all that by authoritative source of Truth we mean that it’s one uh one you and your team treat as the true repo it’s the one that contains the most up-to-date version of the accepted code some people call it Upstream Upstream can be kind of unique uh if you do your repo so this depends on your uh working order some people will have Upstream in a different fashion um so then origin if you’re working in a bigger team you’ll often find that origin is your fork of the of the remote and Upstream is the authoritative one Upstream there you go does that make sense it’s good to kind of know this and you you’ll see this often uh origin is typically the one you uh work with and so if you’re on a small teamworking by yourself you don’t need to do this this would be kind of stupid you just need this uh you don’t need to create a bunch of process for no reason but you do want Upstream when there is a lot of people working that’s when it makes sense Upstream is usually when you’re working from a fork in common F yes yes uh There He Go is that on top of branching yes a remote is a repository right so so we’re going to do that right here so here’s the Syntax for adding a remote and it can be a URI remember a UR URI is very very important to know that so what we’re going to do is we’re going to go like this get remote add origin back up webflix remember a remote is just another repo there’s nothing that says says it can’t be local okay it’s good to know that cuz sometimes people think remotes are only available like on GitHub it’s not true it’s not true it’s not true anyways oopsies I ACD went back all right let’s go forward there we go let’s copy this one all right so let’s copy this thing there we go we have our remote POS uh properly set so we can fetch adding a remote to our get repo does not mean we automatically have all the content so if I go like this get log you’ll know there’s nothing here nothing ain’t there fetch brings in all the changes this is very important so if I go fetch it’s going to bring in all the changes this is fantastic right so if I go like this get log not look what happened look what happened look at it would you look at it nothing’s happened right well the reason why nothing has happened is because we didn’t actually update our stuff and that’s important it didn’t update our branches yet this is good to know this is very very good to know and so we can also go in our get objects and we can find things so I can go like this get uh I can go uh find get uh let’s just find and get you’ll see that up here you’ll see a lot of these things right in here and you’ll be able to recognize some of these there should be a 78 right a 78 in here there you go there’s our first one right there that’s our first commit that’s commit a if I’m not mistaken 7805 uh get cat cat file- p785 look at that look at that a how nice is that huh get fetch money it’s like it’s like it’s for free okay so there you go so you can see that we have all of our commits they’re just not integrated yet so that’s important it’s important to understand that that happens there we go fantastic so now we actually need to uh you know we need to do something about it now bringing the remote uh into this we need to run get fetch oh I apparently I did that apparently I uh apparently this one is it didn’t actually check to see if I did a fetch first easy I ran ahead I ran ahead I ran a little too fast okay I ran a little too fast all right to demonstrate this run get log which we already did we actually already did all that I’m sorry I ran so fast all right I can’t help it so look at this beautiful thing we can actually do this right here you can actually log a remote Branch versus uh versus the origin like we can actually you can see the differences between them as long as we’ve fetched and did all that so pretty pretty exciting time so I can go uh so if I go get log doesn’t work get log main nothing really in there if I go origin main you’ll see all these fantastic absolutely beautiful uh oh did I actually screw up our uh I think I might have screwed up our stuff no I didn’t all right let’s go let’s go I’m a genius I’m an actual genius all right all right merge we can merge branches with a single uh local repo so we can actually merge in the remote Branch yeah yeah exciting what music is playing the music that is playing is going to be bits and something what is it bits and hits which is this is Skyrim but Loi you are a genius I’m not sure about that okay uh can you explain the difference between branches and Upstream Origins origin or remotes so the second part of your question are called remotes remotes oh this guy’s being really annoying here hold on there you go you’re banned forever from YouTube I don’t know how to undo it so if I don’t click this button it’s done it’s forever uh dang it just it literally just left sucks to suck all right uh these are called origins or not Origins these are called remotes now remotes are just repos branches well they’re branches they’re just they’re just pointers to to uh commit within a repo and so there’s a big difference there so an a repo can contain many branches and they don’t have to be the same set of branches branches are just pointers to commits does that make sense so again a remote would be or a repo is just a collection of commits a branch is just a pointer to a commit it’s a mutable pointer to a commit a tag is a non-mutable pointer to a bit uh a commit it took me a couple times to get that right GitHub is just one large gate repo that’s all it really is it really is just one large gate repo they do a lot of really crazy things so all right so now let’s merge this stuff in so I’m going to go like this get merge uh origin uh main so I’m going to merge the main origin into my origin right here uh so if I go get log now you’ll see all the beautiful stuff this Curious Case of Benjamin Button everything’s looking real real nice fantastic so I’m going to go like that I’m going to grab that we’re going to grab this bad boy in confetti time [Music] yes there is no so this idea of local and remote it’s it’s remember git is a distributed Version Control one repo is not somehow the authoritative source and another repo the downstream Source every every repo is its own repo running and you’re sinking between them so you can actually have many authoritative repos it’s just typically to make life super easy you have one which is GitHub and then you pull and push that so everybody can pull and push to the same thing does that make sense there we go all right GitHub blah blah blah blah so remember GitHub is not git is not GitHub GitHub is a product by Microsoft git is a source control GitHub is a way for Microsoft to make money and to scrape your data and to collect it all for the AI in which it’s attempting to create Junior Engineers that cost less but still cost a lot and then to uh and then to use that to get companies to pay them yeah okay now that we understand what github’s purpose is which is to steal your data that’s why they give you free free repos now let’s look at this all right AI alert yeah create a GitHub account we already did this one assignment all right run all checks ensure that your GitHub user exists and is authenticated there we go I already have it I already have it authenticated and all that fun stuff so there we go all right get up repo just like we created webflix local repo and use webflix as a remote GitHub makes it easy to create remotes that are hosted on their site all right perfect we can create a new repo so hold on before we do that I got to go like this GitHub the primin web flick I believe it should be there or did I name it something else I didn’t name it anything so what I’m going to do here settings let me go all the way down to the Bippity bottom delete this suppository I want to delete it uh I have read the instructions uh the primagen SL webflix there we go delete this one holy cow I’m going to need to do I’m going to need to give a stool sample after this to really get everything done whoopsy daisies wrong thing there we go do that thing all right assignment so I may have to darken my screen for this because I don’t know if I have to type and stuff create a new repository on GitHub called this okay let’s do that right now uh go on here actually I can just go right here create new repository let’s call it a web Flix there we go select owner the prim engine there we go create go here we have a new remote right there fantastic looking good oh no we have too many tabs open all right authenticate your uh local G configuration with your GitHub account I recommend installing the GitHub CLI with one quick installation I already have that uh GH authoriz authorization and then do that one let’s see which one are we doing that in let’s see add a remote in your webflix repo there rep points that one okay so that’s webflix get remote add origin for webflix which is right here there we go be sure to place your username and do get LS remote to make sure it’s all done correctly get a uh LS remote there we go I just have that bad boy right there do I need to push up my changes I don’t think I need to push up my changes it doesn’t seem like I have to push up my changes but we’ll find out yay I don’t have to push up my changes all right so there we go get push origin main all this does is pushes up your branches changes to the remotes right so I can actually so with webflix local I can actually push into webflix and so therefore from webflix I can push into the remote um so here just to just to show you that I go like this get Branch uh get switch uh we’ll call it Foo and go get push origin Fu there there we go so if I go back to this guy I can go get branch and you’ll notice fu is now there Fu was just pushed up from one remote into the next that’s all we’re doing is I’m pushing it to a repo and you can put permissions and all that on what can be done and blah blah blah blah blah that’s what that’s uh that’s what it does so there you go the GitHub is not like that crazy complicated in that sense it’s just git the crazy part about GitHub is all the managing and making it scale and all that other stuff uh get Branch uh defu there we go all right all right what do we got to do here do I got to push up all my stuff yeah yeah yeah yeah yeah yeah yeah get push origin main there we go I push my main throw that in there run all checks confetti out of my mind there we go have we gotten to rebasing yet we went past the basic rebasing yeah yeah yeah yeah yeah let’s see pull H fetching is nice but most of the time we actually want the file changes yeah there we go we can go pull remote Branch we already did that in webflix and so if we were to do this again uh we’d be able to do it uh from you know up from the remote let’s use GitHub UI to commit a change to our repo and then pull it down navigate to GitHub uh navigate to Classics uh edit this file add a new line all right so we’re going to do this right here watch this one this is going to be a little bit wild we’re going to navigate to Classics we’re going to edit this one by hand we’re going to throw that in right there we’re going to commit changes and how do we want to commit these changes I want to make sure I have the correct name just in case to pull the let’s see hold on Commit the changes but uh add the message J update classic vs okay there we go J commit changes boom committed out of my mind all right let’s go commit the change using the UI okay we did that on your command line make sure you’re on Branch main merge the changes from update d okay so get check out main get merge uh update Dune there we go uh get run get pull origin which will pull in the most Regent recent command all right get pull uh origin main there it goes it P pulled it in oh no I have diverging branches por Maria I’m not supposed to have merging branches yet this not supposed to happen oh my gosh I have diverging branches I was messing around too much and now look at me now look at me I’m 4 foot2 exactly this is where I give up ah it’s not that bad all right so this isn’t too bad so oh you should also do this oh did I uh did I do that let’s see if you if if you get diverging branches run get config pull rebase false make sure get will uh merge on poll and try again so get status so there we go so if I go like this get config uh list uh GP rebase do I not have it weird I thought I did did I not have that on uh get config add local uh rebase what is it is it pole rebase pole rebase false it’s like I planned I pre-planned for this there we go beautiful right beautiful can we agree with that I did do I I actually probably deleted it by accident there we go now I have a nice merge now I have a merge commit which we you know jeez and so we got a merge commit with a K there we go there we go we did all that one uh make sure everything worked with get log on line uh get log on line there we go a b CDE e f g h i j k there we go there’s my main right there isn’t that nice little annotations by the way origin that’s where my origin’s at or at least where I think my origin’s at this is where I’m at this is where my update do at there we go perfect first commit was in fact not bat man pretty poor move on my behalf honestly not naming my first commit Batman it’s really the way you got to do it oopsies I forgot to do this uh assignment switch to a new branch called ad Classics my bad add another line this one okay we’ll do uh get switch C uh add Classics this stuff is kind of easy I don’t think there’s anything very interesting here that’s going on that’s why we’re kind of just moving rather quickly we’re going to do a poll request if you’ve never done a poll request they’re really not they’re not hard at all they’re very very simple oh my eyeballs there we go by the way did was I supposed to no I don’t think I was I don’t think I was anyways I just want to make sure I didn’t goof up anything all right there we go so we’re going to do this thing we’re going to add the classics um let’s see uh Classics there we go Alfred hitch hok hitch hitch HW Hitchcock Hitchcock uh get status have the classics what do we want to call this thing this is an L we’re going to take the L get add this get commit sorry this this part I I I mean I maybe some people are you know uh find this stuff uh they don’t know how this stuff works to me it’s very very boring right have you ever if you haven’t done any of this stuff it’s very very simple and you’re going to do this can you do a PO request directly in git well poll requests are something of github’s more nature so we’re going to be doing a a poll request you can use the GitHub tools you can’t do it directly from that because git does not know about GitHub if that makes sense all right so there we go we did all that and so now I just simply need to push the new Branch at the GitHub navigate to GitHub do a pull request click new polar request set the base Branch to this one add Classics we want to merge this one create the polar request but don’t merge it yet there we go very very simple so jump in here get push origin ad Classics notice that I do get push remote Branch you don’t technically have to do that if you set up tracking Alfred hitch HW interesting compare there we go add classics classics goes into main create po request bada bing bada boom look at this beauty right here you can see these two things because we’re not quite up to date with all the stuff I’m not reading chat chat is unhinged today absolutely unhinged all right there we go run all checks looking good absolutely unhinged all right my workflow well on this topic of whole request I want to share uh my 90% of the time uh and all let’s see I keep all my serious projects on GitHub that way if my computer explodes I have a backup and I see and if I if I’m ever on another computer I can just clone the repo this is true uh I configured my git to rebase by default that’s why we had that you know this what I do uh rather than merge so I keep a linear history right I like the linear history because I just part of what I’ve always done is I always have this as true it’s just you know I it’s hard for me not to get config um let’s see local uh unset local what is it it’s poll. rebase there we go uh that’s this is what I do I just do this I do very simple stuff when I’m working by myself I just add my changes and push it up you know I think when you’re when you’re working by yourself you don’t need to practice all the greatest things because it doesn’t really matter right uh when I do my team workflow I go on here and I do the ad and I make sure I rebra everything and I make sure it’s all the ways exactly the way I want it to be and I do all that and then I do the the merging is it a good practice to add it to the global uh I I added to local because I wanted local Behavior here I don’t like to do things on the global scope if it’s something I don’t want done for everything since I wanted to turn off rebase I didn’t want to put it globally on in case I forgot to turn it off right so if I go get config global global list Global list we’re GL we’re damn Global list there we go uh re re-enabled see I got to turn that off see I don’t even have it up on here see I must I must have deleted it on axent get config uh add Global uh poll rebase rebase true there we go push on Save of course yeah it’s one of those things that’s really hard to REM it’s why I try to do whenever I’m doing things like this I do it to the local as opposed to the global because I always end up effing stuff up just like that I I I take off all these things and I forget to add stuff delete my feature Branch repeat yep there you go so you know that when working solo do I use many different branches in pquest workflow no I don’t I think it’s a waste of time personally I think it’s it’s a huge waste of time my workflow while let’s see while the topic of PLL request I want to share oh I did this all right when working with the team uh yea Force push no work on a branch feature Branch then open a poll request for review that’s how I do it just makes sense right so if you ever want to commit to open source you obviously need the fork you need to uh create a pull request you need to do all that stuff right get ignore is really really really really really important because obviously node modules if you don’t know about them they’re horrible uh so you need to get ad commit some message here get push origin problems will arise uh get ignore file just simply allows you to say here’s a specific file or a class of files to ignore you can also go with the inverse which is you can ignore every file and then just add the files you want to have it’s kind of like a fun way to do stuff um if you’ve never done that kind of stuff right and so you could have is this the first or second this is the this is the first part so we’re going to create a node of modules or we’re going to create a get ignore file that has node modules in it right so if I go like this Vim get ignore oopsies I already have Vim open here whoopsies we don’t want to do that uh I want get ignore and go node modules modules by doing this if I go like this makeer uh Fu and then I go back to here let’s see and I go back in here and I go in here and go like this uh bar. MD save that and then I go one more and go node modules and I go in here and add uh fu. MD right bam if I go get status you’ll notice something Fu hasn’t been added yet right so it doesn’t have any idea what’s underneath so when I go get add everything and do this you’ll notice that it only adds Fubar it does not add node modules and that’s very important and that’s because this matched anything it’s just a match so you got to be careful careful careful careful include bid and build you coward no another cool thing about G I’m not sure if I talk about this here I’m going to I’m going to go in here and I’m going to erase that right erase that get add this get status you’ll now notice uh node modules is now added right awesome so that means here’s an interesting thing I can do I can go in here and go get ignore you can do uh let’s see let’s go bar anything with the word bar in it get status now you’ll notice we have this and it didn’t really quite do it I believe I had to go MD exact match can I exact match it get add this get status I think because I already added it it causes a weirdness get restore uh staged uh Fu bar. mty get status there we go it’s gone right it doesn’t exist it’s already been staged so I had to unstage it there you go so if I erasee this and go back here get status you’ll notice that it’s now able to be added back so you can actually do inner directory get ignoring which is pretty nice I’m a big fan of that if you want to do it you don’t have to do it but it’s cool it’s cool to know that it’s possible and one last thing that you can do as well is there’s a file called um called uh what’s it called get info exclude you can see it right here there’s the path things that are ignored in here are ignored for your local repo they’re not ignored for everybody and so this is a really cool little file right here if you don’t know about it I’m not sure if I talk about it but you should like say you like for me one thing I always do is I go like this I always I always have like an out file that I always have so instead of adding it to my get ignore I can just add it to my excludes and by adding it to my excludes uh when I so you know when I run some sort of program Echo Fu and pipe it to my out file when I go get status my out file just doesn’t show up but nobody else has to know about my outs ignore I like keeping all the ignores in one place it doesn’t make sense if you’re working on a team right when you’re working on a team I have a bunch of Stupid Files that I create regularly out out to and so I don’t want to have out files inside the G ignore so I put it inside the git uh git excludes list which is kind of like that special one there’s also home get ignore I didn’t know about the home get ignore is this like one uh is this a global project uh ignore see I mean G has a lot of features so I didn’t know that this is the same as a global level get ignore of your work oh cool all right Perfect all right so here we go assignment create two files in your repost secure password. text and create a let’s see first create this thing all right and create that all right we’re going to do that and then guilty pleasures all right perfect get check out main I assume we’re supposed to be on the main branch are we on the main branch yeah yeah yeah yeah yeah yeah yeah yeah yeah uh get status uh rmrf Fu let’s get rid of all this get status all right get add this get stat status uh there we go oopsies oopsies uh what is it called webflix there we go uh we’re going to here I’m going to get rid of that thing get ignore and go in here oh that’s not what we wanted in there we wanted it in secure and then what did he say passwords do text or some crap like that and is that what he wanted password. text yeah and then one called guilty pleasures all right guilty pleasures. MD boom The Notebook let’s go guilty guilty AF finally create a get ignore with both with Ensure both of those files are ignored ignore the entire secure directory and then um all right perfect uh secure and then guilty pleasures all right and then let’s see with the message starting with M all right get commit we got to do a little M message uh get ignore uh my uh my notebook Pleasures okay you don’t know you just don’t even know how good the notebook is all right there we go Nest to get ignores oh I actually already went through this we actually talked about this exact thing didn’t we oh my goodness we already did this all right which is ignored all right hold on what are we doing here here’s the let’s see here’s the contents all right we have these contents uh here’s the contents which is this Source assets get ignore which is going to be only devs and main.py and this one’s going to be Vin bin activate so that one’s going to be this one uh right here and this one’s going to be only Dev and what’s the other one main.py and main.py okay here’s the here’s the contents wait hold on what’s the question which is ignored they’re all ignored aren’t they all ignored aren’t they all ignored does not necessarily have to be at the root it’s fairly common to have this one am I am I misreading things I mean this one will be ignored yeah this one should be ignored and this one should be ignored okay oh oh yeah of course not I’m so stupid okay sorry I’m so stupid this one’s um main pie which does not exist at this level okay I wrote this I actually wrote this this one won’t be ex and then this the grot one has ven has ven V been activate which this one should be ignored as well right am I wrong here shouldn’t that one be ignored just equally whatever there we go only devs I want a main cupcake you can’t have one wrong what am I missing there sell Boozled yeah it’s not one of the options oh act let’s see activate is a shell script not a folder ven is in Source oh V is in Source my bad okay I just wasn’t looking hard enough okay your G ignore file does not necessarily need to be at the root of your project I haven’t looked at this in a little bit okay I wrote that to try to be clear uh it’s fairly common to have multiple G ignore files yeah um there you go we’ve already talked about this one here’s the Let’s see we have already done this one which is not ignored okay so Source ven bin this one okay this makes sense now we got it uh test. Pi which one let’s see test. Pi that one’s not even in there there we go we got it skill issues I’m skill issuing come on shut up uh it would be rough if get ignore only accepted exact file path sections luckily uh they don’t let’s go over some wild card common patterns dude the star that’s the one that’s the one that always works I do it constantly root patterns uh patterns starting with the slash are anchored to the directory containing the get ignore file for example we ignored main Pi in the root directory but not any subdirectories with that negotiation or negation you can even negate patterns with prefixing with an exclamation mark this is useful if you want to ignore an entire directory except say an example file I find that to be really really useful is that that kind of move right there I I really do like that you can do comments that’s just like typical shell comments but how do you make a use of multiple G ignores save some notes or something uh if you want if you just want something ignored a certain way you can do that I found it really useful when it came to uh monor repos so if you’ve ever done mono repos in uh with like node or something you want to be able to have a get ignore for each one of those repos it seems to be really nice that way so yeah data directories yeah exactly you just have like these little get ignores so that way you don’t have one giant get ignore that’s super hard to figure out what the hell is happening instead you can just do that so it’s nice all right assignment use this get ignore file to answer the question uh all right so that’s a comment we’re going to ignore everything with a with a text file except for the ones with name and then we’re going to do Source Main and then content Source content is ignored so this one is ignored Source content MD because this one is an exact file name that matches this one and it’s not anchored so it should be is ignored let’s go patterns it would yes we already talked about patterns we already did all this uh what’s the other question all right Main JS is main.js ignored no it’s not cuz that’s a comment it is not ignored let’s go nice try trying to bamboozle my own questions all right here we go they’re trying to bamboozle me all right assignment Part D we’ll do that soon all right here we go Let’s ignore a generated file we ignore generated files because they can easily be regenerated from stuff we do track in this case we’re going to use pandoc to generate HTML from markdown files we’ll ignore the HTML files uh but commit a markdown file first install pandoc Brew install I don’t have that but we do have this guy I can’t show you guys this screen all right here we go uh there we go look at that look at how good that is look at how good that is fantastic there we go we installed pandoc we can run pandoc version to see what that is so I can go like this um uh pan up uh hashr pandoc uh my password is big boobs everyone knows that big boobs 69420 all right here we go running pandoc all right create a new file at the root directory called advert MD with the following content all right so let’s do advert that one while supplies last there we go uh Vim at oh uh let’s go to this one Vim advert MD paste all this stuff in there we go and then run the markdown let’s see run the following command to generate the HML document from that there we go pan doc Bop get status so now we have the we have this one advert HTML beautiful uh for Fun open up the markdown HTML and see what let’s see we can do that XD I don’t want to do that we don’t want to do that because I had to go like I don’t even think XT xtg open does that work on look at that look at that Beauty look at that be would you look at it would you look at it there we go uh we’re going to do we’re going to do a get ignore I think I have to do a get ignore here oh it doesn’t technically say okay see finally add the file oh the get ignore there we go uh Vim uh get ignore what is it called it’s advert HTML bam get status up get stat get status so I think I should be able to do that nope do I have to add stuff finally add the get ignore oh and commit the change serving with 10 get add get status get add get commit n was it n yeah Foo bar screw it got him there we go I finished it we finished the entire course just like that I’m level 12 you would even understand what level 12 is you wouldn’t even understand it uh what’s your opinion on how organization should handle PR merges in main squash uh merge merge commit or rebase which is most useful when you are responding to an incident which is the most useful for Dev happiness overall in a proud environment well I mean here we go again I know here we go again damn uh I’ll here I’m GNA I’m going to say it this way I personally like to rebase and squash I like Fast Forward merges I like to be prepared for the eventuality I need to uh revert a changes that’s it now some people it depends on your size honestly if you have just a couple people like why even have a policy I’m going to be real out there why even have a policy at all some people like to rebate some people like to merge screw it let it all happen do you really want to set up a whole bunch of red tape for you and one other person like why why why add more to your life here I’m going to throw something out here no matter what you choose merge chaos fast forward merges only rebase squash no matter what you choose there will be a group of people that complain about it so we’re going to start this one so this one is a little bit different okay this one is a bit different this one is going to go over a bunch of like conflicts and stuff okay hey I know you’re about to take learn get to and I really wanted to show you a couple quick techniques to make it a little bit easier because inevitably you may mess up at least some of you are guaranteed to mess up you didn’t read the instructions well maybe it’s not quite as clear as it needs to be and so these are two little commands that are going to help you a whole bunch so the first thing I’m going to do is I’m just going to show the contents of the previous commit that’s going to show Foo with a message of Fu 3 now every now and then you may have goofed up a little bit with your commit message and you just want to change it you can go get commit amend this will give you a chance to change your message but as a warning it does change your Shaw so obviously this is a destructive history altering item it allows you to change the last commits commit message so if I go like this get log one more time you’ll see now it’s Foo 4 and you can see that and if I go get Foo let’s see if I do two of these you’ll notice that there’s not a foo three three in here anymore looking at the change you’ll see that all it is is a new file called Foo previous file was Devol meaning there was no other file so it’s just a new file called Foo with a single line called Fu now if I actually want to undo this commit completely I can go get reset soft head TIY 1 this will undo that commit so now if I go get log just one line you’ll notice it’s not that anymore but because it’s soft and it leaves changes in your index and work tree if I go get status you’ll see right away new file F okay we can work with this get reset hard would not only undo that commit by one it would also remove the file so if you ever have to say change something within a file or you need to change the commit message consider get commit amend or consider get reset soft now I use actually get reset soft quite a bit when I’m doing a rebase merge conflict this does happen every now and then where I’m rebasing and I go okay I fix all my changes and then I actually get commit those changes as opposed to calling get rebase continue if you make that mistake you can actually use get reset soft head till one to undo that commit and then rebase continue it’s kind of like a you know it’s like a it’s a lot of IQ and it’s really really nice so I just wanted to give you those two tips because honestly this course can be a bit meaty and without these two things kind of fresh in your mind you might accidentally find that you get your yourself into a bad State and it’s hard to undo it’s actually pretty easy to undo these bad States the name is the gagen all right here we go let’s do this let’s get going okay welcome to G part two I wrote this also where you learn how to use G with a team if you haven’t taken the first G course I’d recommend starting with it because it contains all these basic operations okay uh the stuff in this course is great let’s see the stuff in the first course is great if you work by yourself but you’ll need more if you want to stand a chance as a developer Mega Corp where we sell synergistic CRM customer relationship Management Solutions to Enterprise that’s right we do hey look I’m wearing the same shirt I’m wearing the same shirt what are the chances uh this course assumes you’ve completed uh number one so you’ll have all this crap that we’ve already done we have already blah blah blah blah so we’ve already done that thing same shirt what are the chances there we go I’m just going to run this because we’ve already done this okay we’ve run it we’ve done it you need your own Fork of Mega corpse starting repo a fork is a copy of this one so we need to go here I’m going to first need to jump in here I’m probably going to need to uh can I fork or is it not going to allow me I can’t tell if it’s going to allow me or not nice let’s go I’ve done it please select owner Fork already exists shoot okay it’s K sensitive today I learned it’s K sensitive there we go I thought I just deleted that but apparently I didn’t delete that there we go and create all right we got the fork we’re forked out of our mind all right let’s let’s let’s do this let’s do this all right so we got a fork we did that we pressed the fork button we did hey look at that hey look that’s me hey that’s me doing that all right boom boom boom boom boom boom boom run check pasting your link we’re going to paste that link all right there we go all right what is a fork uh we created a fork of the official a Corp repo inside your giup account it’s a copy of the original that you can modify without affecting the original you may have noticed that there is no manual entry for get Fork git Fork is not a real thing right why forking is not a git operation but is a feature offered by many GI hosting servfaces such as GitHub gitlab and bit bucket those Services Fork a repo by creating a new copy of the repo and associating it uh as a fork of the original there’s something called like a fork Network or something like that with GitHub which is very confusing it’s like one Super Repo and there’s some sort of thing that they do underneath that’s a little bit more confusing this is gamified git tutorial this is a g tutorial I wrote and I’m going through when you Fork someone else’s repo on GitHub you simply clone their repo into your local machine you create a new branch of The Originals well technically I think it has something to do with this in the fork creation network but I don’t really know how it works create a copy of your own let’s see of the repo and your own GitHub account boom let’s go that’s what we did all right I’m not working TC no okay GI Fork is a command line operation that takes no f false all right now let’s clone it down let’s clone Mega Corp uh RM RF let’s get rid of webflix let’s get of webflix local let’s get of uh Mega Corp Mega Corp uh get clone the primagen get clone get clone primagen Mega Corp Bim we’re in we’re in we’re in in there we go perfect all right we’re we’re in okay so let’s get let’s let’s start doing this whole thing because this is this is the one that in involves a bunch more stuff uh when you Fork someone’s a repository like a platform like GitHub you can copy a repository into your account this is the standard way to contribute to someone else’s open source project uh steps are typically Fork the repo to your account clone the fork to your local machine create a branch or feature make the changes commit the changes create a poll request bada bing bada boom you’re probably asking yourself why should I Fork a repo instead of cloning it cloning is a lot easier well that’s a good question you first have to answer the question am I interested in contributing back to the main line or do I just want to peruse the repo if you wish to just simply peruse the repo then a clone is just fine whereas if you wish to contribute to the open source project then it does require a fork here’s usually my workflow when it comes to forking and making changes one I just Fork the repo two I will clone down my forked repo three I’m going to make the changes to my main branch four four I’m going to push my changes up to my Fork’s main branch five I’m going to open up a PR with my changes from my Fork onto the original repo along with a nice detailed explanation of what I have changed and why and finally I get rejected go home cry a little bit skill issues but nonetheless I tried and that’s what really counts doesn’t it it’s also worth noting that whenever I clone down my Fork I also add a second remote that I call Upstream that points to the original repo and the reason is that when the original repo changes I can bring in their changes and that way when I fix something I know that I’m fixing on the latest version I’m Not accidentally fixing something somebody else has already fixed this also avoids having conflicts during PRS and if you wish for your PR not to be rejected here’s some pretty helpful hints number one whenever I make a PR before I hit that button and say make it live to everybody I review my code on GitHub this weird thing happens to me whenever I review code on GitHub I seem to catch things that I don’t catch when I’m in my own environment I kind of think of this as editor blindness you’re so used to everything that when you see it in a concise different way you just see mistakes you’ve made so much easier probably most importantly is make sure the maintainers want these changes spend the time looking through the repo issues make sure you’ve searched and validated that this really is an issue and if there’s no mention of it open up an issue tell the maintainers you’re willing to fix it and see if they want you your fixes you may find that maintainers actually do not wish for you to participate or others they may want you to fix it but in a completely different way as long as you’re polite in your communication and you’re very clear as to what you’re trying to fix you will find that often maintainers are very happy to have you come on board and help out okay so assignment I want to make sure people know how to do this okay I want to make sure people knew how to do this like fun little bit add a file in your forked and cloned version of Mega Corp to the repo uh to the repo contributors directory uh the file should be named let’s see your get up username text replace your username with a good one okay let’s see add myself to the contributor okay Bam Bam Bam Bam Bam Bam Bam Bam let’s go in here and go here okay well I’m already there the primagen 2. text oh my gosh oh my gosh all right there we go there we go we got that let’s do that let’s go like this get add uh uh get whoopsies all right there we go so we’re going to push this up right so I’m going to do all this I’m going to push this up push my changes to my GitHub uh to an add contrib Branch oh gosh get checkout add contrib oh I’m not supposed to use checkout sorry it’s just I can’t help it I can’t help that I do who the hell does that who Noob Noob Noob he’s a noob I’m not even sure oh I I copied it from the boot. dev site remote add origin all right there we go fixed fixed you wouldn’t understand understand fixed you wouldn’t understand you don’t understand because you’re you’re you’re sore loser boom I think it told me to create a pull request let me just make sure that that’s what we’re doing here all right there we go all right with the poll request open submit the test all right there we go run all checks let’s go owned it head mean where me at now for those that don’t know who grug is grug is the best I always go down here and just I just read this line whenever I think of gr grug apex predator of grug is complexity complexity bad say again complexity very bad you say now complexity very very bad given choice between complexity or one-on-one against T-Rex grug take T-Rex at least grug see T-Rex complexity bad all right let’s go like this okay for example you should be on main branch of your local clone of your fork of Mega Corp repo which which means head is pointed to the main branch like all things and gets eternals head is just stored in a file right here manually uh check to see what’s in head yeah let’s do that cat uh get check out main get cat uh dog I think it should be I think it should be the name of the thing there you go yeah it’s just a it’s just a path path to the uh to the branch or the tag if I’m not mistaken G yeah you got to G it baby you got to G it get that son of a bee all let’s see if that just works okay what did I I didn’t read all right what’s the thing oh uh get Branch d add I must have missed deleting that did it say to do that okay my bad I didn’t look I did not in fact look we’re going G grug no read all right get reflog command pronounced a reflog not reflog is kind of like Get log but stands for reference log and specifically logs uh the changes to a ref that have happened over time T the default one is the head by the way grug no read grug never read where head is now one move ago two moves ago three moves ago you are already familiar with how git log Works how it shows your current branch and all the history of the commits so if I had a brand new repo with three commits a b and c and I execute log I should see the following output and if I execute ref log I should see this following output is reflog just a verbose log well no it’s actually not it’s very very different and to illustrate the point let’s remove commit C I can remove commit C by using git reset I can walk back one branch and as you can see with Git log I now only have b and a but if I use get ref log you’ll notice that I don’t have two entries I actually have four entries I have a b c then back to B and notice that it contains the command I use to get to B which means that if you need to get the contents of C you can actually use some of the plumbing of git plus reflog to be able to retrieve back out the contents of C even though it’s gone from your branch I cannot tell you how many times reflog has saved my bacon by walking back and getting some commits that have been long forgotten so what is reflog well the definition from get SCM is reference logs or ref log records the tip of branches and other references whenever they are updated or in layman’s terms reflog tracks the changes of a branch or other references other references being head this means as you move your head around from Branch to branch or from commit to commit it tracks every last little step I personally only ever use reflog to look at how my head has transitioned over time and Rescue out of commit if I need to all right assignments run get reflog to see what its output is all right here we go get ref log look at that look what it is going from ad contrib to main from uh from Main to ad contrib to this commit to the Clone cool right you get to watch it kind of move around it’s kind of cool I like it reflog is nice and it’s really not all that bad all right switch to a a new Branch off of it called slander get uh switch C slander look at that I remember to use that uh let’s see create a new file called slander. MD and have this one all right Vim slander. MD paste that in uh Mega Corp CEO Lane enjoyed the live action last air bender movie this Mega Corp CTO Prime is a fan of the notebook okay Lane mayor or may not had a little bit of fun editing some of these things okay I don’t know if I didn’t choose all of the stuff I’m just saying you know the notebook’s not a bad movie okay what I feel I even have to commit it okay it’s not it’s not bad okay it’s not bad Ulta movie was a good terrible movie too did you cry I didn’t cry I’m not crying SL slanderous slanderous filth I’m not even sure if I spelled slanderous right um boot. Dev run that okay what am I not even doing here all right expected this contains all this one oh I had to do b. slander goodness gracious uh reset soft uh head I okay I got to start reading you guys are not helping me um uh be slander you guys got to quit but by the way did you see that nice usage of get reset soft huh ha did you like it I could have get commit amend I could have we could have amend but this one is great okay it’s okay it’s okay to cry it’s I don’t cry I work out I know we could have amend okay but we didn’t okay delete Branch every ever uh shipped a bug to production main branch created a new Branch to fix it bug fix fixed the bug and committed the changes switch back AC deleted deleted the fix bug Branch all right switch back to Main and delete your slander Branch get Branch D whoopsies get check out main get Branch oh I’m supposed to use switch but I I just I can’t I cannot use switch okay I can’t use switch I can’t I can’t use switch all right I want to use switch Boomer brain I know so you’ve deleted your branch that had a unique commit On It All Is Lost or is it remember get reflog keeps track of where everything has been so let’s do this get ref log look at this bad boy that’s where we did this one look at this commit right here the commits right there the commit is right there okay that means what we could do like here’s one one way to do it which I’m not saying this is the way you should do it I’m just saying this is one way you can do it you like this you can go like this you can go uh get cat file- P remember when we learned about all this and you can actually go through all of the little internals and snatch out the slanderous file get cat file- P look at this right there there’s me enjoying the notebook right we were able to Plum through things if you wanted to if you wanted to get deep in there and kind of go through the whole thing you could so there we go we grabbed that and so we can actually grab this and do that and do a recovery message right so I could do this right there’s other ways I could also do stuff right this is just one way you could also get merge and since I already have this thing I could actually just merge over that change into it we’re not going to do it but you could imagine we could do that so instead I could just take the contents of this one file and I can remake it if I wanted to as well even though it’s not true commit that file with B recovery get add this commit dashb Rec recovery Boom Confetti out of my mind all right cherry pick would have been what I would want to do really I would have just merged it over right I mean it it just depends do you want the history or do you not want the history like what happened if there’s 10 commits then you have to cherry pick all the commits let’s see using get internals is exceptionally inconvenient we had the copy and paste from cat file three times I would not recommend doing it this way I just wanted to drive home that at this point you can always drop down to the plumbing commands if needed luckily there is a better way get merge I just haven’t talked about Cherry commit that’s why we haven’t talked about that so I can do reflog this one find the commit kit that one so I can do get cat file do all this crap which we don’t want to do I can also do this right right I could have just merged over exactly what it said from reflog right let’s see do I still have that reflog thing or did it open it in one of those windows uh I think it did that one of those windows right yeah do I do no pager no page I can never remember what that line is oh that’s right you don’t do it there it’s a get no pager there you go so as you can see you can see right here so I could actually do get uh head at the second position back right why does get ref log allow us to potentially recover commits on deleted branches because it keeps a record of where the head has been yes that’s what it is there you go little fun little fun reflog stuff merge all right let’s see what can you merge with only tags commits branches a commit commit tag ref log entry anything that can resolve to a commit so that’s why you’ll see me use the term commit quite a bit in this [Music] course all right uh working with Git is a dream when all of the developers in the project are committing changes to different lines of code things get a little hairy when changes are uh to the same lines are made at the same time one commit isn’t the parent of another let’s break some stuff remember Mega Corp is Enterprise CMR Service uh backed by the power of git Essen it means that we store lists of customers data in a get repo truly Cutting Edge stuff you should be on the main branch uh create a new branch called add customers all right get branch no wait it’s get is it get switch see there we go all right there we go we got that one and we’re going to grab this one uh to customers a CSV all right all is it all like that one yeah there we go so we’re going to add it to all customers and then we’re going to also do orgs partner. text right there Boot and startup so we’re going to do orgs partners. text there we go beautiful we’ve done those two make commit your changes with the thing C okay we’re we’re going to kind of cruise through these easy Parts because I assume at this point you guys understand adding committing doing all that um because this is all easy stuff right none of this stuff is crazy all right get status get add this get commit I think I said c right yep see uh uh such Carson much HDMX all right there we go and now we’re going to switch back to Main and we’re going to do this to customers uh get check out main uh go back to here edit this thing jump up here customers all add Json gross HTM Z contributor get add this get get commit what do we need to do with d That’s right d uh Jon is better than uh Carson more like cars off all right so do you do you see what we’ve just done here do you see how this is going to cause problems so if I go like this uh get log uh on line um on line- P1 main you’ll notice that I edit customers with one line right below company title if I do the exact same thing but I do it uh with the add customers Branch you’ll notice that I do the exact same thing to the same customer files in the same location in other words we both modified the same line and by modifying the same line G doesn’t know what to do because git doesn’t understand anything about code it only understands things about modified lines if two lines have been altered in some way it creates a merge conflict there we go I believe that should just work there we go and let’s go conflicts yeah yeah yeah yeah yeah yeah yeah so merge conflict occurs when two commits modify the same line and get automatically decide which changes to keep and which change to discard consider the following commit history ABC this is pretty much what we have now except for it’s a c and d uh the main branch has something like this uh is nice returns this one feature has this one is nice 420 right if we try to merge feature into main G will detect that the return line was changed in both branches independently which creates a conflict so this is good this is good to understand right when a conflict happens usually as a result of merge or rebase git will prompt PRP you to manually decide which changes to keep it’s okay when the same line is modified in one commit and then again in a in a later commit the problem arises when the same line is modified in two commits that aren’t in the uh in a parent child relationship all right if the line changed in B was all the conflict change in B’s parent a the htx guy writes an essay about it that’s true Carson will probably write an essay about it uh that’s perfectly fine get knows a happened first then be yep that’s the thing you can’t conflict yourself like that right you just can’t all right if two developers on separate branches modify the same line of code what happens when the branches are merged HTMI htx guy relaunches the project with a new name facts it’s perfectly fine false conflict arises there we go assignment it was stupid Greg stupid Greg who merged his new customer data into main commit D while you were working on your new customer data in ad customers Branch commit C because his change made it into main first stupid Greg it’s up to you to resolve the conflict stupid Greg now because your manager is a lite that learned a code before Version Control was invented he asked you to merge instead of rebase absolutely this is all true switch to your add customers branch and merge main into it all right there we go we should get this one let’s go let’s go get check out add customers hey uh get Branch d add uh add contrib wait why is contri still there I thought I just deleted it why is there why is there multiple ad customers whatever that’s confusing whatever I don’t got time for this damn it Greg leptos mentioned leptos potentially mentioned get merge main all right boom we got ourselves a conflict okay uh if we run get status you can confirm that we’re in a conflict so if I go get status you can see right here you have unmerged paths fix the conflicts and run get commit and use a get merge abort to abort the merge so we can actually stop the merge by doing that get out of here okay there we go get run status like this to confirm that you’re in a conflict we can see that so let’s run this thing boom Oh wait what oh my gosh this thing is incorrect lane lane Lane we have a problem this is this is wrong our Direction somehow got out of conf out of out of stuff here I know which means I go like this get uh merge abort get check out main get merge uh get merge uh add customers there we go kind of BS Lane all right right here I’m going to go back here I’m going to report this uh wait does it am I wrong here did I just maybe I just didn’t hold on get uh merge get merge aboard get check out maybe I did this wrong yeah I used the wrong one lane it’s not right lane you’re right you’re right this whole time I’m the bad one I’m the bad one I’m the bad one shut up get check out you dumb folk I know I messed up isolate to changes and merge correct you merge yourself correct resoling conflicts is a manual process when they happen get marks the conflicted files and ask you to resolve the conflict by editing the files in your editor so here we go open up the customer all and you should see this all right so here we go here’s our customer so you can see two you can see a couple things here just so everybody knows in emerge conflict this represents uh hours is the top one hours is where our head at here’s the change in hours the change ends with the equal sign and then this is the one and then the bottom one represents the incoming Branch theirs so theirs is main ours is head and this is the change in theirs this is the change in ours okay it’s pretty good to know those things right uh let’s see delete the conflict Mar markers and leave both changes and Greg’s changing the file it should look like that so we can actually you can actually have both changes at the same time right nothing says you have to change it it’s up to you to resolve how to to do this you can accept both totally reasonable uh sa file and do this okay yeah we can we can accept both there’s nothing that says you can’t accept both right all right resolution after manually adding any conflicted conflicting file sometimes it’s more than one file or more than one section of a file you simply need to add and commit the changes this tells get that uh you’ve resolved the conflict and can continue with the merge okay awesome we can do that so let’s let’s resolve with this nice message right here it’s a nice beautiful message get add this get commit uh- M all of that oh my goodness stupid Greg oh no all right there we go apparently I don’t know how to do that there we go got it first try and now we can do log to examine the homework you should see c and d and commits come together and E commit all right get uh log on line look at that beauty and then we can go on line graph there you go it all comes together in E we resolved the conflict bada bing bada boom very nice absolutely liked it absolutely enjoyed that all right all right you just ran get merged and you’re now seeing this okay I just realized what was happening I was like wait a second uh which code in the conflict is yours and which is theirs so if we ran get merge that means this is ours this is their theirs the top is the top is mine the bottom is theirs it’s all mine stay away I prefer that answer honestly um all right you just ran get merge and you’re now facing this conflict oh let’s see what does head refer to it’s another name for the master branch no it’s another name for the main branch no it points to the latest commit in the other Branch you’re comparing to no it points to the current Branch’s latest commit boom it’s pointing to where head points to everybody knows that is that easy back to me your manager at Mega Corp is not happy it turns out you were never supposed to add customers to the all. CSV file at all only Greg is allowed to do that stupid Greg this is what you get from making changes without 10 design meetings and an alignment of stakeholders what were you expecting to be productive this is Mega Corp process over productivity get back in line I don’t want to hurt anybody’s feelings but at the same time I know a lot of people just got bruised by that one statement I’m sorry I’m sorry that right there’s some of you that hurt that paragraph hits home I know it does let’s just say I’ve written a design document for the the dumbest thing stakeholders are okay in the 10th design meeting but have problems when the implementation hits BR always every single time assignment let’s fix our hastiness by uh doing a git hard of the merge commit this will allow us to take a different approach to resolve the conflict luckily we haven’t borked main yet we just uh need to fix our ad customer Branch while on ad customer Branch reset to commit C all right let’s do that oh my goodness um let’s go like this let’s go what is it called Mega Corp yeah yeah yeah get reset uh hard uh head till the one there we go we’re back to C everything is great we’re looking good we’re feeling good there we go we do all that nice stuff so I just I I literally just took the change moved back my Branch ones and discarded my index my work tree changes bada bing bada boom easy peasy pumpkin seedy that’s just that all right uh let’s fix our hastiness by doing a hard reset yeah we already did that luckily we haven’t borked main yet so we’ll just uh fix all right here we go try merging main into customers again this time resolve the conflict by keeping only the changes for main I want to see something cuz I may accidentally have uh R re on and if I do then it’s going to say it’s all fixed nice I don’t have R re on uh get config list uh Global grap re re oh I do wait shouldn’t re read take care of that doesn’t wouldn’t Riri re jump into that am I confused here am I be what what I thought it did well then why didn’t it it should have Auto conflict it record yeah record resolution was solved was added weird Why didn’t it just Why didn’t it auto resolve right here shouldn’t have just Auto resolved oh wait oh oh my goodness I am so stupid I am so stupid it did it automatically using previous resolution so if I go to customers oh my goodness I’m so dumb look at this the conflict is gone the reason why the conflict is gone is I knew I had re re-enabled so since the customer doesn’t have a conflict in it we need to disable R re get uh config I’m just going to do a local one uh I’m just going to go like this add local re re re enabled false right so I’ll just add a local one so I still have my Global one so it still continues to do what it’s doing uh get merge abort then get merge um get merge main which should now there you go I now have the conflict without re taking over and I should be able to just go into here uh and I should be able to go to all and now we have this again so now this time we’re supposed to select Greg’s change which is theirs so I can go like that boom Greg’s change selected uh there’s some other ways you can do that to make it easier but this is good so we’re going to go like this find Greg have this one boom uh we’re going to go here and go get St status get add this get commit dasm with that one there we go um and then jump in here do that there we go there we go all right I think that’s good all right ours versus theirs uh in a merge conflict ours refers to the branch you are on merging into theirs refers to the branch being merged this is important get merged their Branch ours is the branch you’re on right uh get terminology last time we manually edit the conf uh conflicting files this time let’s use get built-in merge resolution tools to make the uh let’s see use the terms hours and theirs to refer to the branches being merged you should currently be on ad customers with this kind of History right now switch back to Main and merge ad customers into main this would result in a fast forward merge bringing C to e into main delete ad customers all right get check out main get merge add customers get Branch delete uh add customers boom look how fast I am all right so let’s do a better let’s do an ours versus theirs merge because this is really good to know uh all right so we got a multi conflict so far we’ve only dealt with one Conflict at a time that’s a small that’s small potatoes let’s see what happens when we have multiple conflicts to resolve all right so let’s switch to a new Branch off Main called delete records uh get switch C that uh and then let’s see edit customers all and delete the jesson line okay there we go deleted it edit org partners and delete the boot dodev record okay org Partners there we go boot dodev record boom Oh we want to keep the line there we go uh let’s see six let’s see switch back to main uh and edit customers oh commit the message with f we got to commit the message with f get status so I’m going to I’m going to use uh I’m going to use what’s it called fugitive for this part cuz it’s just easier and faster and you guys don’t really care about committing right what do we need to do F uh F uh uh delete those records right I just prefer that uh get check out main just makes life easier being able to use that because we can move faster there we go uh all right so we have this one so edit the ORS partner and add a boot dodev record uh to Sales Inc oh change it and change the boot to Sales Incorporated yeah yeah yeah yeah yeah yeah yeah yeah so I can go like this Sales Inc um there we go we did that one so now we should have this one and do a g there we go and uh ccg uh such Inc there we go we now have that one run and submit the test there we go wait is that all we had to do did I miss something I thought I thought we were doing multiple oh we forgot to do that we forgot to do that one we forgot to do that one Carson uh gross that’s right all right uh customers all and go Carson gross go here s there we go so I just all I did was I just did right there for those that don’t know I just did a uh I did a get uh commit amend no edit and so by doing a get commit amend no edit I simply just um I know I wrote shut up shut up it just means I merged in that change right so I merged in that change right there and I did that one you know cuz I’m not going to lie to you it is very nice to be able to use the tools I’m used to you know what I mean I don’t always do everything by the command line there we go all right so we did all that one we have these nice commits now we have these two things and so now all we have to do is just cause the conflict let’s go wait what did I do oh oh my goodness here I forgot to do that there you go I’ll show you what I did get status so I have this one get add this one get commit uh amend no edit there we go so I kept the same the same uh line just not everything else wait what am I doing wrong here Carson grow hmx Creator what I’m not good at reading I’m not good at reading okay I’ve never said that I was good at reading all right first try let’s go first try check out the conflict we’ve manually edited files to resolve the conflict but it turns out git has some built-in tools to help us the git checkout command uh let’s see can check out the individual changes during a merge conflict with theirs an ours flag while on Main merge delete records all right get merge delete records so now we should have two conflicts you can see the two conflicts right here get status you can see the two conflicts right here unmerged path both of those get diff should show each one of them having the problem right here which means that I can go like this uh how do we do this we’re going to keep theirs for customers all and keep ours for partners so I can like this get check out theirs uh that’s going to be uh customers uh all there we go so now I have uh theirs and then ours is going to be orgs uh Partners there we go so now if I go like this get uh diff you’ll notice that we have no changes everything looks good get status perfect get add this if we look at them in here you’ll notice right away there we go so that’s the deleted one that we kept and then from orgs and partners you’ll notice that we have Sales Inc from our side so Sales Inc from our side deletion from their side by using uh get checkout there’s an ours hours it’s pretty nice what do we need to do here we need to do this with an ah uh M uh H uh let’s see such uh resolution conflict you’ll also notice something else notice that orgs is not a part of any changes here do you see that there’s no orgs a part of changes that’s because that wasn’t changed by accepting my change this commit doesn’t contain any change does that make sense because that file only had one change to it which was my change so by me uh accepting it the difference between these two goes to zero it’s good to know so that’s why sometimes those things can change and it can look a little bit confusing it’s actually not all that confusing it just means that something goofed up oh my goodness how am I so bad at this oh yeah let’s go all right something you may have noticed when resolving merge conflicts is that you don’t get the standard merge uh merge commit message right no you don’t you have to manually provide a message typing uh it actually makes sense when you think about it g doesn’t know what you did to resolve the conflict and it’s encouraging you to document your change via the uh message that makes sense right I think everybody understands that uh what commit message is used after resolving that the standard one unhinged commit message for example we should have rebase instead I actually like this one that’s my favorite one but we’ll do a custom commit [Music] message now we’re going to do rebase one this one’s going to be a good one all right rebase uh full disclosure a lot of rebases bad rep comes from conflicts fear not it’s nothing you can’t handle with just a SCH smidge of practice rebasing feels scarier because it rewrites get history which means you are not if you’re not careful you can lose work in an unrecoverable way but as long as you understand what’s going on it will make your and your teams get history cleaner and easier to understand and more so easier to revert when needed it is impossible to revert your change with several merge uh merge commits and all that I’ve seen some pretty nasty ones where you’re trying to do that assignment create a new branch called band a copy of main branch and add a new file customers band all right there we go scabi toilet merch when get checkout dasb band I didn’t use switch didn’t use switch it happened it happened but we’re going to get keep on going for it band. MD is that what it was no uh band. CSV boom put it in yeah Sam Sam controlman closed AI classic really true AB absolutely actually true there we go so we have this one we’re going to do get message I so I’m going to go in here c c i uh control man there we go and so now let’s go like this get check out main do one of those and then how do we want to do here we want to have the same Sam controlman but a different but a different one of these there we go um and then jump up here and go c h oh no wait J you’re right H comes before H before I except after C’s right is that how it goes I’m on chapter 7even section four right now all right well let’s go let’s go all right so there we go so we have all this one so we should be able to run this to make sure it’s all actually the way we want it to be so I’ll go like this we’ll run this bad boy it’s going to do all this bada bing bada boom bada bing bada boom all right beautiful we are just crushing through this course okay people were feeling good make the conflict before we move on I just want to remind you that it is often uh not often that you’ll be creating your own conflicts we’re doing so because you probably don’t have any friends to practice with I don’t actually Kid Art users uh but even if you do have many developer friends let’s just make all the changes ourselves so you don’t need to bother them let’s see you switch to a new Branch fix bug which is just a copy of main while you’re fixing the bug someone else merch is there changes the domain you fix the bug and it happens to edit the same file uh you open up a poll request rebase fixing domains get tells you the conflict you resolve the conflict you uh complete the PO request this is like standard operations right we all know this one so we switch the band Branch rebase uh it into main uh which rewrites to get history of band Branch because remember it needs to add that extra commit so there we go we’re going to do that all right so we’re going to go like this get check out band right there get re rebase main my gosh we have a conflict look at that conflict oh no oh no so if I go in here I look at my status you can see right here we have problems don’t we we actually have problems all right well uh you should get a conflict you might also notice something odd this time head pointed to Mains change rather than bands change all right so let’s just jump back for a quick second and just validate this and I’ll explain why all right so notice that this should be band protagonist should be main look ate has protagonist which is Main’s change why is ours Mains even though we did a rebase on band why why isn’t hours hour change why is it Maine’s change does anybody know the commit comes from Maine no cuz that would make it’ make it theirs we move to main then replay our commits on it boom let’s go so this is from section one this is why section one is so important is when you rebase your target Branch becomes your branch that you’re on and then you replay the source branches commits starting from the merge base and forward at the tip of your target Branch therefore let’s write this out because it might be a little bit easier to visualize so this is the most important part remember so when I’m on band and I do git rebase main what happens is I actually check out main which is going to be at the tip I grab the differences between uh uh what’s it called band and Main and then I do band you know if there was multiple commits I’d actually attach each one of them to the front so that’d be like band one uh band two uh band three right so I’d get them all on there so my Branch now looks like this where the tip of main is now the new merge base as opposed to wherever I branched off before which could be somewhere in the history so that is why ours is theirs and theirs is ours during a Reb rebase conflict it’s actually not confusing if you know how rebase works it makes perfect sense it’s that you have to switch branches and then play the commits all right let’s see what happens here let’s let’s see what our assignment is switch the new branch do this uh copy of branch and add the new file customers this this this this this we’ve already done this all right there we go assignment switch to band rebase on domain while uh you should get a conflict you might also know something outd we already talked about why if you had merged main instead of rebase head would still point to band correct because merge does not swap replay it just adds or creates a merge conflict into a single point there we go that’s good to know however you kind of need to think in Reverse with rebase theirs represents the band Branch uh which in reality is our change so we’re going to Branch you’ll notice that you’re not on a branch that’s right that makes perfect sense right because remember it has to create this no Branch situation where it takes Main and then starts applying commits to it so you’re in a no Branch situation right there we go bam look at that look at that confetti man first try first try uh the same get check out theirs and get check ours uh commands we used in merge can be used to resolve conflicts during a rebase you may have also noticed that if you open the file in your editor depending on your editor uh it has UI features to help you resolve the conflict yep so this would be uh VSS codes accepting incoming changes is the same as checkout theirs accepting current changes is the uh is the same as get checkout ours that would be in theirs I don’t know how I don’t know how to use I don’t know how to use vs code all right assignment uh use the appropriate get checkout command to overwrite the band Branch’s changes with the changes from Main so since it’s main that we want get uh status get checkout out hours our Branch remember we’re ding main all right there we go uh let’s see then hit him with the rebase continue get rebase continue There we go and then we get logged to see the new commit history get log look look at how good that looks look at that look at how good that looks all right you may have noticed something did anyone notice that I was gone why was I gone so theirs is main no ours is main during that situation the the number of rules indicates that this isn’t intuitive no it just means that it can be potentially complicated anything that is sufficiently complicated requires you to learn if you only worked on things that are intuitive you would never use recursion like that’s that it has nothing to do with it being the the number of rules have no indication whether it’s intuitive or not understanding the underlying reasoning why or what happens makes it intuitive to understand I understand how you or rebase Works therefore ours versus theirs is intuitive to understand but that’s because I have a understanding of what’s Happening expected a state to contain this way H uh Branch oh I’m not oh I haven’t uh oh uh get rebase continue oopsies did I not get status did I not there we go we’ve continued it gets status awesome all right let’s do this perfect we’re in we did why did the deleted command what happened why was I gone so for those that don’t understand so why where’s I why is I not in here the reason why I is not in here remember this is that I was a change where deleted deleted a specific record and what we do we ignored that one change by ignoring the one change that I was we’ve dropped the entirety of the record since the there is no like there’s no empty commit when the commit is empty the commit is dropped right yes we are working on the band Branch we started a rebase of band onto Main meaning we’re rewriting the history of band to include all the changes of main we effectively removed all the changes of the I commit by choosing to keep the changes from Main instead of band we continued to rebase and get realized that the I commit was pointless because we’re rewriting history anyways just remove it there’s literally nothing in it right there’s no I in team that’s why if our if our changes had been more complicated say we kept some of the changes from I commit and overrided others then git would have kept I in the commit history why did git remove our commit because this is Mega Corp and we have a strict no commit policy uh because rebase is scary and it should be avoided at all cost because it was a essentially empty and rebase is okay with rewriting history bada bing bada boom there’s nothing to commit there’s nothing there it’s just making life easy right uh what if the only part of the commit had been undone during the rebase comp what if only part of the commit had been undone then the commit would have still been let’s see would have still been removed no the commit would have remained in the history let’s let’s go on to this one okay let’s clean up our branches remember during these uh during the rebase of band onto Main we actually discarded the changes of band which actually means that band is now just identical to main anyways so yeah so we’re going to switch back to Main and delete uh band right uh get check out main get Branch D band there we go all right so let’s delete some branches we’re going to delete uh get a branch okay we did that one and now let’s go over here let’s go there we go all right let’s move on all right disable re well uh we it should have already been disabled this this section does need to technically go back cuz already did a local one of those uh I here I think I don’t think I deleted this I’m not sure if I even have it but here I’m going to get rid of it just in case right repeat resolution setup a common complaint about rebase is that there are times when you have to manually resolve the same conflict over and over again this is especially prevalent when you have long running feature branches and even more likely multiple feature branches that are being rebased onto Main re re re to the rescue the get re re re functionality is a bit of a hidden feature by the way this is directly from G sem can you believe that one of the most useful features of all time is just hanging out uh here hold on uh get R re re there we go let’s go get SC look at this functionality is a bit of a hidden feature wait you’re telling me I didn’t have to resolve it every time yikes the name sound let’s see stands for reuse recorded resolution as the name implies as the name implies it allows you to ask G to remember how you resolved a hunk conflict so that the next time it sees the same conflict G can resolve it automatically in other words if re let’s see if enabled a re will remember how you resolved a conflict applies to rebasing but also merging and will automatically apply that resolution the next time you see the same conflict pretty neat right am I right all right assignment create a new Branch off of Main called faves all right good check out B faves didn’t use switch suck it new commands create a file called uh faves. MD with the following contents let’s go uh jump back in here go here go here wait customers okay customers uh faves faves. MD there we go cool uh commit that with message K create a copy of faves branch called fave 2 all right here we go uh we’ll go in here we’re going to go here we’re going to CC we’re going to K uh ma faves is the uh heisen right boom boom get check out dasb faves 2 so now we have the same Branch twice okay okay the same Branch twice all right now we’re going to switch back to uh Main and create a file called faves with a different content all right here we go get check out dashb main get U Manny main oh crap I created Manny get check out main get Branch D Manny got him first try uh and then go in here and put and put that in there and get status get add this get commit dasi what is it called should be with an L take the L take the L bam all right so now we have these right here we have main on L faves on K faves 2 on K the the changes from L and K naturally conflict run the test let’s go we’re going to run the test we’re running the test let’s go we’re running it confetti out of my mind are you ready for the confetti out of my mind enable the re re feature by running the following command all right so I’m just going to like this get uh get config unset local re re re enabled cuz I have a get conf config uh list grip re re re there you go I already have it globally true for everything because I like the setting switch to faves and rebase it on to main all right get check out uh faves get brand or get rebase main there we go so notice this we’re going to do this conflict we’re going to be doing this recorded pre-image for customer there we go we’re getting ready we’re re re reing okay so we have a conflict let’s do this let’s solve this conflict notice out let’s see hold on accept both changes all right let’s accept some changes okay e yes yes yes changed get add this get rebase continue all right so now what are we going to do with the naming um stage and rebase leave the commit message as K all right boom got it note that git May automatically open a file on your editor in which you can edit the commit message Simply Save and close and continue when you’re done you should see something like this so you should notice that we should see something like this recorded resolution recorded resolution yeah we’re read out of our mind we’re read out of our mind now switch to faves 2 and rebase may it on to main all right get check out faves to get rebase main now look at this we have a conflict but it’s already resolved right it’s already resolved because we already we already resolved this specific commit so now we don’t have to resolve it again it already knows what to do it already knows what to do so now I can just I can do the exact same thing I can do the whole get uh rebase continue so R is really really nice because it’s one of those things that if you do it right it is uh fantastic uh why is re disabled by default because it can lead to confusion so if you don’t know what it is it’s probably dangerous to have it created what’s foot comes with Riri let’s say you have a change that results in a conflict but you want to resolve it differently but instead it automatically resolves it for you you could feel pretty confused right so that’s why it’s nice to have it as a feature you opt into because that way you don’t accidentally screw it up all right let’s go on merge back in PH now we have two branches faves and faves 2os that are ahead of Main in the same way we don’t actually need both faves and faves 2os so switch back to main try deleting fave 2 with lowercase D flag now actually delete it with capital D we’ve already we’ve I think I’m not sure if we’ve actually done that get check out main if you don’t know if you go if you try to delete a branch that ends there it terminates uh your commit history it’ll be like yo um You probably don’t want to do that and so you have to give them the old you have to give them the old capital D and when you give him the D it then does it then merge faves into main this should result in a fast forward merge deletes the faves Branch there we go get merge faves get Branch d uh faves boom let’s go grab it paste it all right accidental commit uh you know uh how let’s see how with merge uh conflicts you can commit the resolution but with rebase you have to do continue dude I’ve done this so much in my life I cannot tell you how many times I’ve done this dude I know I’m telling you which is me telling me I cannot help this one how do you undo that dude get res dude this is the greatest thing in the universe right there this solves that problem if you ever accident you’ve never done it really oh my gosh when I re when I when I get when I get rebase when I when I resolve a conflict I do get ad dot it immediately I go get ad rebase or get or get commit Dash app and I commit it and I’m like and I just hate it but if you just do a reset soft remember a soft takes the commits changes applies them to your work tree and moves your branch back once so you get all of your you get your rebase right there now I believe this has been largely fixed I believe now you can actually do a rebase uh continue even after you’ve committed it and it just works you just get that you get that new message instead before it used to not work I love this one why does get reset help you if you acent commit during a rebase because you can undo the commit and continue the rebase yes exactly that’s why I love it okay we’re going to go over a quick bit of squashing okay every Dev team will have different standards and opinions on on how to use git some teams require all poll request to contain a single commit While others prefer to see a series of small focused commits if you join a team that prefer single commit you’ll need to know how to squash your commits together to be fair even if you don’t need a single commit squashing is useful to keep your G history clean yes and it makes it easy to revert again if you have a feature that could be dangerous in production and it’s spread out over 12 commits that have like 18 merge commits it is really really annoying versus just having one commit at the end score squash it easy to put in easy to pull out okay what is squashing exactly well sound let’s see it’s what it sounds like we take all the changes from a series of commits and squash them into a single commit okay all of them A B C D to ax easy assignment let’s get ready to squash some commits push your current changes up to your forked repo on GitHub just in case your machine goes swimming don’t skip this okay here we go get push origin origin main go all right uh create a new Branch off Main called temp main get check out temp m-b let’s go all right so now that we have that we do all this let’s go let’s go we’re back in um to be completely fair I I mean I am just absolutely I I have what someone oh get checkout DB temp main yeah there we go all right how to squash perhaps confusingly squashing is done with get rebase command it may not be intuitive but remember re base allows you to apply or reapply history this will make sense more here’s the uh steps to squash the last end commits start an interactive rebase with get rebase head uh or slash or Dash ey I think they call it tack ey in the military get rebased hack I head till the end where n is the number of commits you want to squash get will open your default editor with a list of commits change the word pick to squash or S save and close the editor the I flag stands for interactive and allows you to edit the commit history before get applies the changes head till the end is how we reference the last end commits head points to the current commit there you go does that make sense uh why does rebase squash remember rebase is all about replaying changes when we uh rebase onto a specific commit end till the or head till the end we’re telling get to replay all the changes from the current branch on top of that commit then we are using the interactive flag to squash those changes so that rebase will apply them all in a single commit assignment Mega Corp Executives do not like your last few commits as a result your manager told you to squash the last three commits J L and K into a new single commit message J redacted squashing is destructive operation which is why you’ve decided to make the change to Temp main before moving it to main while on temp main squash these three don’t forget to pick or squash it and edit J redacted let’s go uh so I’m going to go like this get rebase or first get log so we want to go all the way to J so 1 2 3 uh get rebase I head 3 Let’s Go so I always go like this there we go you’ll notice right here it says it right here that you can do that s stands for squash use the commit and meld it into the previous so that means s uh go let’s see how does this go it goes this let’s see this one goes into the previous and then this one I forget how exactly how these things end up but either way it ends up it ends up good I forget the exact merging order uh redacted right there we go there we go so if I go get log uh one line you can see that J is redacted and the rest are all right there perfect right but they still can change the change set so if I go- P it still has the whole change set it just doesn’t have uh what’s it called it just doesn’t have the individual commits all right override now that temp main is in the state you want and hopefully you verified that with Git log we need to do uh what the boss asked delete the main branch rename the 10 Branch into main ensure that t main branch is gone resubmit now obviously this is a very dangerous operations we rewriting public history we’re doing it just for fun because hey why not uh but we’re doing it okay so don’t don’t do that by the way Branch delete main get check out um get oh don’t actually do uh temp main main this is this is dangerous okay there we go we did some naughty stuff we squashed main which means that because our remote main branch on GitHub uh has commits that we removed git won’t allow us to push our changes because they’re totally out of sync git push has a command called Force flag which allows us to override a remote Branch with our local branch it’s very dangerous but useful flag that overrides the safeguards and just says make this Branch as same as the branch so by doing this we’re actually changing that stuff and that could be obviously you would never want to do this to a main okay just so you know go ahead and force push your local main to the branch on remote main uh I know by the way you should never actually do this okay this this is this is crazy okay squashing is scary when you squash commits for example ABCD and you into a single commit you’re removing history from a project so all the changes are still there but the individual markers of each changes are gone it’s one big commit now in the last few lessons we erased all the commits meaning we can’t go back to the individual checkpoints anymore or you can’t go back easily we can still use git plumbing and reflog to actually rehydrate everything and reput it back into it we can but we’re just currently not doing that when you squash commits you lose history of the individual commits that’s what happens you can still get it back it’s just that it’s just non-trivial right when you squash commits the content stays the same correct the content stays the change it’s just that you change the commits yeah never squash Master never squash master I put that in there so I could talk about it and why it’s crazy we did some weird thing squash commits to m now let’s do a common thing squash all commits on a feature Branch for a poll request if your team prefers single commit poll request we will likely be your workflow create a new Branch off Main go about your work when you’re ready to get your code into main squash all your commits into a single one push your branch to the remote One open up a poll request merge it uh once it’s approved all right assignment first let’s just do points one and two Mega Corp needs to add a new feature to the content management system specifically they need a script that will automatically scan for sensitive information in the repo create a new Branch add scanner off of Main all right this is where things are going to get a little bit wild here get Branch or uh check out dasb I know it’s switch I can’t I don’t want to do it I don’t want to do it I’m too much of a lite um all right in the scripts directory there’s a file called scan sh replace uh the to-do comment with this all right I can’t help it okay all right in the scripts uh thing scan f8 write the script there we go we got it um all right there we go we have that one run the code from the root repo all right look at that we have oh my gosh we have so many social SEC or credit cards so many co credit cards just flying everywhere finally now we can do social security numbers add another few lines to the script all right there we go uh run the script again to ensure it works oh did I not oh I forgot to commit oh I forgot to commit I forgot to commit hold on k um uh credits there we go wait why isn’t that working oh did I did I actually delete oh crap all right there we go now we can paste this in there we go all right there we go so now I can go CC and this one should be J right this should be L yep okay so this one will be L um this one will be uh Social Security numbers my bad my bad I accidentally did that one out of order now we should do phone numbers there we go add add one for phone numbers added it for phone numbers there we go there’s some phone numbers in there CC uh and this is HJ K LM uh phone numbers there we go looking good run the script one last time make sure it works there we go all right I actually uh I accidentally uh I accidental your commit I know happens there we go all right so we got ourselves set up for this nice next one squash series remember the full workflow we’re going to be doing which we already talked about this creating your branch making your commits squashing it making the pull request let’s tackle point three squash uh KLM into a single uh new commit starting with k remove L&M all right so do it again get rebase I head till the3 do these ones uh SS there we go and go into k there we go Bam Bam Bam Bam got those two uh we are rewriting the history of our own uh Branch let’s see to make it look as if we did all the work in a single Commit This is normal and fine because it’s our Branch yes it’s our Branch now it’s okay to do right now it’s okay before it wasn’t okay to do and we did it on Main which we shouldn’t have done it on Main but it’s give me something to talk about give me a reason not to do that our Branch all right so now we’re going to do four and five uh use get push to add scanner and open a PO request all right get push origin uh add scanner there we go we’re going to do that and we’re going to go to back end we’re going to go to GitHub the prime gen which update Mega Corp and there we go P requests new pull request add scanner let’s go create pull request create it let’s go looking good looking good oh my goodness how do you not have my repo name I thought you had it all right I’m just going to copy that one and bring it back in here and go the primagen there we go and run all checks oh am I doing it oh uh to main on your mega Corp oh crap I did on I did it on your mega Corp I didn’t read the instructions good I in fact did not read good instructions here I in facted terrible instructions reading there we go uh apparently I can’t change uh where my remote is pointing to which is kind of weird that’s fine GitHub the prime engine um mega Corp there we go so I effed it up I effed it up apparently the UI doesn’t let you change the base reading instructions are required for squares yeah losers add scanner there we go sorry the previous one didn’t require me to required me to do it on a different one so it got me a little bit confused all right there we go merge the poll request remember we did all that one now let’s tle pack point six merge your pull request from uh ad scanner into main you can also do so by clicking the Big Green merge request button uh when you’re done you switch back to main branch locally here’s the scary part delete your local ad scanner Branch pull the latest change it from Main and your local main branch should have a now commit K yeah some people get freaked out it’s okay when you have centralized merge stuff it’s not a big deal hit the big green button confirm the merge get check out main get Branch Big D delete add scanner right boom get it out get uh pull oh my gosh I didn’t set I didn’t set that there we go get pull my Branch wasn’t pulled there we go look at that good yeah there we go we got the energy we got it all done absolutely fantastic it’s all in all right wait did that mean I did it [Music] okay stash all right so now we’re going on to stash are you guys ready for some stash all right you’ve been at Mega cor for a while three whole days and to your mother surprise you’re still employed here’s the workflow you’ve been using as a junior developer commit some let’s see commit some changes to a feature branch open a poll request from that feature Branch to Maine check out the new feature branch and and start back to the next task today however is a big day all right today is a big let’s see big day let’s see the customers are complaining about a critical bug and the CEO saw you first she asked you to drop everything and fix it immediately but you’ve got a bunch of unstaged changes that you’re not ready to commit yet and you don’t want to lose what do many git noobs would create a second clone of the git repo at this point a huge mistake you’re better than that that’s right you are better than that uh the get stash command records the current state of your working directory and the index staging area it’s kind of like your computer’s copy paste clipboard it records those changes in a safe place and reverts the working directory to match the head commit the last commit on your current Branch to stash your current changes do get stash yeah and stash list to list your changes don’t look at that my stashing workflow looks a little something like this I usually have some amount of work that’s in my index or my work tree and I get a request in that says hey can you please investigate this bug or hey you need to pull in the latest changes because if you pull in the latest changes the feature you’re developing will have a couple extra apis that you need which means I’m going to have to take my changes create a commit pull in the new changes finish off the change I wanted to make create another commit then squash those two commits into one or I could just stash my work tree and my index pull in the changes and then pop off my stash when I need to get back to doing what I was doing and finish the change I was trying to make now the the times that I don’t do that approach the times that I don’t choose stash which often I do is whenever I had to pull in a change but I’m already in several commits into a change I’m trying to make typically I try to keep my changes pretty small but every now and then you’ll have like a thousand line change and whenever I have a big change like that I try to make small commits along the way as nice checkpoints in case I screw something up so bad that I can just roll back to the last known working commit and then start again so if that happens I simply make another temporary commit rebase in my changes and then at the end of everything I’m doing I already have worked in that I’m going to squash everything down to one commit anyway so it doesn’t bother me all right assignment while on Main update readme.md in the root of megga Cort repo to do this one B bam just after updating read me uh that the CEO approached you stash the changes once you’re stashed make sure that they are uh safe in your list let’s see they are safe by listing now it’s okay you would be able to single see a single stash list okay all right um let’s go into here let’s go to read me uh let’s let’s see let’s delete that and go to this one there we go GS we have look at this look at this we have our read me but bam we got to stash some changes so I’m going to jump in here and go uh so for those that don’t know get stash all it does uh is it takes whatever you were doing and puts it into like a special area it’s kind of like uh it’s kind of like it it’s kind of like a commit uh so if I look at get status you’ll notice there’s nothing there get stash list uh you’ll notice that there is one right here if we go get stash list I believe it’s- P you can see the change right here right it’s just like a special place to be able to put changes for a moment I never use it longterm if you use it long term you’re crazy don’t do that that’s absolutely nutty to do right absolute nutty to do all right stash has a few options get stash pop list the pop command will by default uh apply your most recent stash ENT to your working directory and remove it from the stash list it is effectively UND does the stash command it gets you back to where you were this is called a stack and that’s important okay pop your stash change back out you should see it working get stash uh pop so it’s a stack and that’s really really important to know because if you push two things on top of your stash you will have your latest one on top the stash command stores your changes uh in a stack Pho data structure also I wouldn’t say uh I wouldn’t say Pho okay I’m last in first out I’m more of a lifo kind of person Lane again your copy editing hurts my feelings here I’m a lifo not a pho or not a I’m a lifo not a pho yeah for sure that means that whenever you retrieve your changes from the stash you always get the most recent changes that’s true bada bam uh Pho is greater than lifo W Lane false all right stash is a collection of changes that you have not committed they might be raw working directory changes or they might be stage changes both can be stash for example example make some changes to your working directory stash those changes make some more CH let’s see make some more changes without stage them stash all of that when you do that the stash entry will contain both staged and unstaged changes and both your working directory and index will be reverted to the state of your last commit it’s very convenient way to pause your work and come back later git stash is a very convenient feature of git in which allows you to store your index and your work tree into a special area known as the stash and then later on to be able to pop off those changes and reapply them to your work tree /index but what is the stash well it’s a data structure that is a stack so every single time you have a change to your index SL workor tree and you want to save it for later when you call G stash it actually creates something that’s like a commit and adds it to this data structure pushes it onto the stash stack any files that were not a part of your index slthe work tree will simply be ignored when you call get stash pop it’s actually going to take the last thing that you added to the stash and apply it to your current work tree /index X that means if you stash three changes a b then C if you pop something off you’ll be popping off C then the next time you pop off it will be B then the final time you pop off it will be a if you’re unfamiliar with a stack it’s actually pretty simple think of a stack of plates if I add a plate then add a plate then add a plate if I wish to remove a plate I would never try to grab from the bottom IID just grab one from the top then the next one then the next one Whatever order you put in is the reverse order of what you take out in other words it’s a last in first out data structure you can inspect your git stash by simply executing git stash list which will show you in the order in which you pop out your stashes often I use the stash in a very one-dimensional way I have some changes that I need to pull in from Main so I’m going to stash my current changes pull them in pop off my current changes and continue on my work I never use the stash as like a long-term storage place just because my code changes so fast that it often gets out of date super quick what is not staged unchanged uh unstaged changes to the track let’s see to the tracked working directory stag changes committed changes you can’t stage a commit okay you can’t triple triple stamp a double stamp if you push three sets of changes into the stack let’s call the first one a the next B the last one C what happens when you run get stash pop the changes from C are applied to your working directory but the stash entry is not removed the changes from c i remember clicking this last time it got me this changes from C are applied to here working directly and the stash entry is removed let’s go multiple stashes you can stash changes with a message I rarely use stash in fact I never use stash messages that I can remember I’ve used it like once or twice the big reason why I don’t do that is whenever you’re doing this this means that you actually want to come back much later which to me just says this needs to be a branch in which you keep somewhere and then you can edit the commit if you want to you can rebase the commit uh for me stashing is a very very like temporal operation assignment restash the changes to readme with the message good marketing update the readme uh file again with the following contents right get stash uh message uh good marketing boom right and so we’re going to go back here and I’m going to go delete and I’m going to have this one there we go now let’s see stash those changes with bad marketing uh get stash bad marketing there we go and now we should do a stash list get stash list you can see these two different ones right here so that means if you add a p in here you can see the difference unite Marketing sales and service in a single app try Mega Corp starter Suite today there is nothing uh to install no credit card required the only thing standing between you and more customers are you are your terrible salespeople get started today it’s a pretty good that’s a pretty good one that’s feels good feels good all right so there we go all right unrelated commit now that you’ve safely stashed your current work let’s tackle the CEO’s urgent matter CG uh Mega corpse APO script or shell script truly is a feet of engineering it behaves exactly as the shell borne shell language but with the word let’s see but if the word shell or sh is ever mentioned in the standard out it will replace it with APO it’s a feature that customers love but it’s not working let’s see test by running scan with the APO language for Shell there we go we’re going to grab this one there we go so you can see it right here it’s all right there okay uh the grap command let’s see the grab command should filter out the output to the lines that contain sh uh you should see a couple lines which means APO sh isn’t doing its job uh the culprit is this line yeah yeah it should be replaced with SH not bash all right we’re going to update the script we’re going to update the script right all right let’s update the script man customers love just the craziest things huh uh scripts Apo there we go wait a second there it is we got the Apex okay you’re right get status get add this get commit get commit L the L stands for lovely reading the primin there we go all right now that we got that apply without removing from the stash so you can actually do that I’m not really sure the purpose of this but it does exist uh you can apply without or you can you can remove from stash without applying this makes more sense Lane W Prim L yeah I know it happened reference a specific stash so you can actually do it in one of these locations with the at sign so that means we probably we’re going to have to do the one run uh get stash list see what uh see the stashes you have apply the changes from good marketing stash index without REM moving it from the stash list so we just have to do a little apply do one of these bad boys get stash list um paste that in there one there we go uh get add your changes to the index drop good marketing stash pop the only remaining one bad marking you should notice that you have a conflict resolve it by keeping the changes from good marketing stash commit the changes M all right let’s do that uh get stash drop um stash uh at one there we go get stash or get add this get stash pop wait oh whoopsies uh hold on get what happened get status did I miss what happened here uh Vim read me there we go I missed the message that said it it did the wrong thing so there we go I’m going to remove the bad marketing one call it a get I missed the conflict message how did I miss that oh it’s right there it was right there the whole time I just missant again it’s that reading thing you know what I mean okay it’s that reading thing that really gets me [Music] okay all right revert when reset is a sledgehammer revert is a scalpel uh revert is effectively an anti- commit it does not remove the commit like reset but instead creates a new commit that does the exact opposite of the commit being reverted it undoes the change but keeps the full history of the change and it’s undoing so it’s kind of like the Spider-Man thing you know I mean grug reading for a living but grug no read yeah I know it’s sometimes you feel right all right to revert a commit you need to know what commit the are the commit hash of the commit you want to revert you can do it with Git log all right and once you have it you do a little get revert hash with a committes assignment uh in your great haste of pursuit of greatness at Mega Corp you forgot to write a white paper and get approval from the l69 distinguished staff architect for your marketing documentation change the l69 has requested you revert the change and sure you are on Main revert commit M it should prompt you to write a commit message and we’re going to call it n let’s do it all right so we’re going to go like this uh get log one line so what do we need we need this guy right here bam get revert that one and save get log on line you can see right here here looks like this get log um on line- P2 so look at this you can you can see that it’s literally the inversion of it the starter repo for the G course 2 that one removed it this one added it back this one added this this one removed it this one added that that one removed it so it’s like an inversion so that’s what a revert does it literally does like an anti-matter commit to your history and then it turns it into a commit so you actually have it as a part of your graph Oh shoot that’s not right right that’s not right that’s not right did I mess that up I must have messed that up yeah see it says get revert M okay that’s my bad uh get commit uh amend all right there we go that was my fault that was my fault still doesn’t read I still I literally cannot read the get diff command shows you the difference between stuff differences between commits and the working tree Etc I frequently use it to look at changes between the current state of my code and the last commment um I use it to look at I I primarily use it to look not at that I primar well I mean yes actually that’s exactly I my current state sorry that red funny what my current changes are I rarely use it for uh staged stuff if you want to do stage you have to do dash dash staged uh show the changes between the working Tre the last commit uh you can do that you can do difference between branches you can do difference between two hashes I’ve tried to do this for bigger ones in bigger projects once you get to a certain size it’s like impossible diff the changes between n and M commits remember n is the version of changes and paste the full output in here get diff uh a head till one I believe is all I need to do I think I can’t remember submit boom yeah there we go bro do you even diff I diff I diff okay just copy P into notepad Plus+ with the differences extension wait what why would you do that revert versus reset reset soft undoes the Comm but keeps the uh stage changes undoes the commit and discards the changes revert creates a new commit and undoes the previous commit there you go when to reset if you’re working on your own branch and you’re just undoing something you’ve already committed say you’re cleaning everything up so you can open a poll request then get reset is probably what you want however if you want to undo change that’s already on the shared branch especially if it’s an older change then get revert is the safer option it won’t rate any history and therefore you won’t step on your co-worker toes don’t look at that don’t look at it when do you use reverse versus reset well they’re actually quite different operations so you just need to understand them fundamentally and it’ll become obvious when you use one versus the other whenever I use reset it’s because I want to be able to take a commit undo that commit make some edits and recommit and in the case of get reset hard I actually just want to throw away that commit this means I’m working on my own Branch not on a branch everybody else uses I’m able to edit the history and get it into the way I would like it to be whereas a revert is more for the public Branch what this means is that you have a problematic commit and you need to be able to remove that commit but you could never do that to a public branches it’s going to break everybody so instead you make like an anti-matter commit right this commit contains changes a this one reverts changes a and this also has the added benefit that if you want to go back in time you can go back to a and actually fix the bug and then reintroduce a along with its bug fix now I find that I revert when I’m on a larger team because often you’re in this position where where somebody needs this change to go out such that a new customer feature or a new Ab test that’s high priority has to get out but your changes have broken the build and we’re not discovered until we released into production so we need them out right away there is no waiting there is no waiting to fix forward so therefore you simply revert your commit fix the change create a new commit with the fixed code and all the changes back in and then next release your code can go out and hopefully it’s not broken but if you find yourself reverting a lot it’s likely because you have a pretty unhealthy process your cicd is not up to Snuff your tests aren’t quite there your automation is no good production is the ultimate place to test but it should not be the only place you test which creates a new commit revert let’s go Which rewrites history [Music] reset all right there we go cherry pick everyone loves cherry pick this comes a time in every developer’s life when you want to yink a commit from a brand but you don’t want to merge or rebase because you don’t want all the commits get cherry pick is another one of these very useful git operations but you infrequently need to use it cherry pick is when you want one change from a branch but you don’t want the entire history of the branch you only just want say a singular commit or two commits Where cherry pick is obviously useful is when you have a branch that’s called release and then you have your main development line every now and then release gets cut and that Branch gets updated now let’s pretend you’ve been going in their there’s hundreds of commit in Maine but we discover a bug in production well we can fix the bug in Maine and then just transfer over that one in singular commit to release and then reproducti release thus fixing the bug but we don’t contain all of the changes from Maine because those changes are largely untested or may they contain half-baked features that are not ready to go out quite yet so This Is Where cherry pick Works a switch to a new Branch off of Main called ad Partners update the partners organization to be this one commit the changes with o update the same file again with P all right let’s do that uh all right get Branch let’s see what branches I have all right cool get uh check out dasb still not doing it still not using it Lane was just like we should use switch and I was like dude I’m all About That C about that c get check out I just didn’t I can’t help it I can’t help it I I just I just have to all right there we go won’t sub if you don’t use switch nope then don’t sub I’ll ban you how about that one how about that one tough guy get commit d o okay the setup we’re going to do the setup my face oh than wait yes so now we got to do p all right uh Vim Partners uh dap paste let’s go here get status get status get add get commit dasp on the electric fence huh little call back to Ren and Stimpy I think I spelled fence wrong whatever that’s close enough you know what we’re close enough that’s a little Ren and Stimpy call back okay it’s been a long time since I’ve watched some Ren Stimpy okay close it enough all right what theme of V code is this you know exactly what theme it is can read nor write all right how to cherry pick uh first you need to clean uh clean working tree no one committed changes identify the commit you want to cherry pick typically with get log is a good one run get cherry pick commit or commit would be better get log to grab the first uh of the two commits we just made oh that’s the one we want get log there we go I’m going to grab this bad boy my oace then we’re going to go in here cherry pick o on to main ensure that it let’s see it worked by checking the partners one delete add Partners boom get Cherry uh pick that oh I just did it onto my own thing get uh get status it uh I didn’t even change branches uh abort abort abort boom oh my goodness I have a revert in Pro oh my goodness wait how am I how do I have a revert in progress how did I do that okay when when when did I do this all right hold on uh get log all right so I have the revert right here all right so that’s already been committed so that’s not a problem get uh get Branch we have our two branches I’m on Main uh let’s see no Cherry pit oh I have a board am I actually calling aort oh dude I’m so stupid I didn’t even see that I was doing aort okay I am really not reading it’s been a long day I don’t know if you guys know this but I’ve been streaming for track hours nine hours okay it’s been a long day all right there we go so I moved over this right here so I can go get log DP so we can see right here closed ml one of our favorite startups right can’t even read the timer okay shut up shut up it’s been so long I’m not good at doing this much this much stuff at a time all right we need to delete the ad partners get uh Branch delete ad Partners there we go the man’s losing I’ve lost it I fully lost it I’ve lost it I’ve lost it let’s go first [Music] try oh yeah we’re up to bisect do you like bisect you guys you guys want a BCT all right so bisect is fantastic let’s do this okay let’s do this get bisect is yet another get command that does sound quite intimidating to the uninitiated but once you learn how works it is actually quite simple get bisect allows you to find a commit in which introduced a bug really fast and it does this by using a technique called binary search let’s just pretend that we have a branch that has many commits on it our latest commit contains a bug and a 100 commits ago does not contain the bug how are you going to find when the bug was introduced well you could go step by step through it until you find where the bug’s at but that would be tedious if it takes couple minutes per try it could take all afternoon or multiple days but since commits are ordered by time in which they are merged we can actually pretend they are an ordered array and do a binary search across it so this is how git bisect Works let’s pretend that we have a known state that is bad and a known state that is good and we have a bunch of commits in between all of this we’ll call it X amounts of commits if we test the middle commit and let’s pretend we found this middle commit is good we know that all of this is good in other words we’ve cut our space in half we have x / 2us 1 left commits to check and if we repeat the process we can continue on finding smaller and smaller regions to go check for our commits if we find one of these are actually bad then we know that all of this direction is bad and we repeat this process until we’re able to find a singular commit that is the commit in which the bug was introduced if x was a th000 it would approximately take us 10 checks to find the bug and using git bisect is really simple you set the good commit you set the bad commit you say start and it will start doing that exact same process of cutting the known space in half asking you if this commit is good or bad if you answer good then it knows all the commits earlier are good if you answer bad it knows all the commits that are ahead are bad this can save you days of searching so we know how to fix problems in our code we can either revert the commit with a uh the bug this is more common on large teams or fail forward by just writing a new commit that fixes the bu this is more common on small teams well it’s if you have the time that’s the this is the ideal in my head is to be able to always fail forward right that is my favorite uh but there’s another question how do we find where the bug was introduced that’s where get bisect command comes in instead of manually checking all the commits that’s Big O O right Big O N I mean get bisect allows us to do a binary search which is login so that means after like what 10,000 it’s only 14 checks it’s the way to go so if you don’t know how to do bisect you bisect is fantastic if you’re working on a slightly old code base that has thousands or hundreds of commits right all right let’s see BCT isn’t just for bugs you can do anything so the nice part about this is anytime you have a change you’re looking for and you have a script that you can check then bi sector can be used to find where that say Improvement and performance Improvement was Ed introduced performance uh regression was introduced anything so bisect is fantastic the B the purpose of bisect is to split the repositories into two separate repositories split the commit into two find a commit that introduced a bug or change say it that way uh a commit to find a change that was introduced there are seven effective steps to bisecting that’s it there’s only a quick seven now you know you know me from reading right am I right you know my skills at reading so we’re about to go deep on this one okay yeah yeah all right start the bisect with get bisect start select a good commit select a bad commit uh get will check the commits between them and find it execute uh get BCT good or bad to say the current commit is good or bad uh loop back to step four exit with this one get bisect receip or uh reset there we go assignment your boss just chewed you out because the scan a sh script should never have been added to the repo not only does she want the contents of the script erased but she wants to know when the script was added and for you to fix it with get revert so the history of your Royal screw up is preserved considering you can’t remember when you wrote the script you decided to use get bisect start BCT you know the head commit is bad so Market is bad you know the first commit a is good so mark it as a if the script content is pres uh present not just a to-do comment Mark the script as bad otherwise mark it as good repeat step four until get bisect completes it should give you the hash of the commit all right so this should be pretty easy do you understand here right boss should have been in code riew yeah I know boss boss yapping but boss wasn’t wasn’t reviewing that’s what I’m seeing right now people lot of yapping not a lot of looking uh all right let’s see revert the commit that introduced the script with commit message P am I right am I right all right so let’s find out when that happens so we’re going to go like this I’m going to do the following I’m going to go get uh Buy uh um start right so we’re going to start it waiting for both good and bad commits so I’m going to go get a BCT uh bad so that just says oh did I BCT there we go I literally could not see the difference there bad so you don’t actually have to provide a commit if you want to use the current one so there we go I just used the current one uh get log one line go all the way down to the bottom get uh BCT good we know is somewhere right there so now notice that it has six rever Visions left uh to test after this roughly three steps so we can go we can go cat uh scripts scan word count line all right so there is one line so this was just the to-do right so when it has one line it is the to-do okay so that would be get bisect good we like that one this one has 10 lines so that one’s bad this one’s bad all right this one’s so this one’s also bad all right this one’s good I’ll explain what’s happening in more detail here for a second there we go you can see exactly where this has happened and you can even see right here K credits so all right I think this is good uh get log DP this thing you can even see right here this is where the changes were made to the uh scan script so what actually happened there it’s actually not that bad you can imagine that at a that’s our first commit and I forget what our uh head is right whatever commit that was head how a bisect actually works is that remember each Comm has an ordering to it this is an ordered array therefore the ordering of course being merge order or it’s going to be like say time and so that means we’re going to go b c and all the way up to head that means if we check the middle element and it’s bad that means this entire side is bad but if we check the middle element and it’s good that means this entire side is good so since the first one was good we know that all of we know that all of this let’s see hold on shoot which one is that if we know this one was good we know that the rest of these were good right here so that means we went in the middle of this one so then when we checked here and it was bad we knew that all of these were bad so then we went into the middle right here and when we checked this one since it was bad as well we knew that all these are bad so we went and checked right here and since that one was good then either the one right after it since there’s only one commit left between these two it was able to say that this one was the bad one it’s a binary search that’s effectively what happened right sorry for my fairly shoddy explanation but that’s all it is bisect is really simple right it’s it’s it’s really easy you can think of this like an ordered array imagine you have an array that goes 1 2 3 4 5 6 7 8 and you wanted to find out if it has the number six well what you could do is if this is zero and this would be uh8 right the ending it’s of length eight you could do 8 minus 0 ID two which gives you four and you can check this one is this six no it’s not is it greater than it is since it’s greater we need to check this one okay that means we need to update our lower bound to this one so now that’s going to be three 0 1 2 3 we still have eight as the length so we do it again what is 8 – 3 / 2 which is going to be what two 2 and a half two then add it to three so we got to go to five which is going to be four five is this one it yes it is we’re done say we’re looking for seven then we do the exact same thing again which we’d have to go to Five 8 – 5 is 1 divide by two that or that’s three divid by two that’s one add it to one all right seven check here is this it yes it is good so that’s all it is it’s pretty easy um binary search is really really easy to do right and it’s great it’s actually really really great so that’s all bisect was doing was that so now that we have that we’re going to go like this uh get uh BCT uh reset oh my goodness BCT I I I can’t read that word get uh revert that one p there we go sounds like successive approximation well whenever you have an order you can search the space more efficiently given an input if you don’t have an order you cannot search space efficiently that’s why things like uh that’s why eventually you just have to do a linear search through everything if you have no order linear is quote unquote slow linear is slow but it’s not as bad as like quadratic or uh even more that was annoying now imagine if testing wasn’t as simple as just looking at a file manually running an automated test can take a long time as compiling uh a gasp J Java Enterprise project absolutely uh for the man get BCT you can do bisect run now this is cool okay bisect run allows you to be able to do that process we just did but in an automated way now this is very important because sometimes you have to sit there for 30 minutes for something to tell you if it’s correct or not so it’s much nicer to be able to just have this thing run and then you go play I don’t know play game basketball whatever you do I’m not sure what you do okay so there we go there we go let’s create a new script in scripts called BCT sh with this contents so that means if we find scanning in the scan we exit with a bad exit code if we don’t find it we exit with a good exit code in other words uh BCT when you run it uses the exit code to determine if it’s a good or bad build so let’s go in here Vim this thing up go into scripts go BCT Dosh go in here do that make it executable uh I prefer to hit a oh yeah I guess I don’t need to do I don’t need to do a shebang there we go and now I need I can go into here and do the exact same thing and I can run this script now so I can go like this we already chimed it we can do a bisc start and go get uh get BCT uh start get BCT bad get BCT good that there we go so we have our head to our tail and now we’re going to run through and do this thing even though technically we’re doing a bad with our current one you know there’s a little bit of something weird here so I can go cuz we reverted it so technically our head break our whole ordering but don’t worry about it we we can skip that get bisect run um scripts bisect and I believe we don’t need to yeah there we go we don’t need to provide any arguments so when we do this one there we go it found it is able to run that script super fast and find it immediately there we go and now we know where the problem was see bisect is pretty cool what does automating bisect require uh an automated test that can programmatically inform git if the current commit is good or bad that’s pretty much it there we go all right work trees uh we’ve been saying work tree all throughout this course but I have been misusing it I am sorry it’s not technically what we’re on is not called it’s not work tree precisely uh it’s the main work tree which is more precise because you can have more than one working tree what is a work tree a work tree or a working tree or working directory is just the directory on your file system where the code you are tracking with Git lives usually it’s just the root of your git repo where the dogit repo is it contains tracked files untracked files modified files right everyone know everyone can fundamentally understand what a work tree is your main working tree just makes sense the work tree command get as a work tree command that allows you to work the work trees the first subcommand we’ll worry about is simple get work tree list it lists all the working trees you created all right so let’s see what working trees we’ve created you’ll notice there’s only one working tree right yeah which is my current my current work tree right linked work trees uh we’ve talked about stash temporary storage for changes branches parallel lines of development clone copying an entire repo work trees accomplish a similar goal allow you to work on different changes without losing work but are particularly useful when you want to switch back and forth between two change sets without having to run a bunch of git commands not branches or stash you want to keep a light foot print on your machine that’s still connected to the main repo not a clone so this work trees effectively allow you not to have to clone out a repo for a second version of it there’s some like requirements there’s some rules I think I go over the exact rules in here the main work tree contains a git directory that’s important with the entire state of the repo heavy lots of data in there to get a new main working tree requires get clone or get a knit uh a link work tree contains a git file with a path to the main working tree it’s effectively as light you can think of it as almost as light as a branch it’s just like a little bit heavier than a branch U let’s see uh can be complicated to work with when it comes to end files and secrets this is where things kind of usually go off the rails for work trees is work trees can be a pain in the butt when you have uh say node modules node modules can be really annoying so we can create a new work tree like this we do this uh whenever you do a path on an ad if you do not include a branch name it takes the the uh first baster of the path and uses that as the branch name and it’ll actually create it so we can create a linked working tree uh as a sister directory to your main working tree called alra Corp uh use the default Ultra Corp Branch so watch this so I can go uh oopsies uh get uh get a bict uh reset forgot to do that get a work uh tree ad what is it it’s path which is going to be let’s call it Ultra Corp there we go so prepared to new work tree it’s called alra Corp so if I go here back out and go Ultra Corp you’ll notice that Ultra Corp is on Branch alra Corp because that was the Bas that was the first base dur of the path that I did so if I would have done like Ultra Corp SL fuar then the branch would have been bar if that makes sense and so now if I go like this cat get you’ll notice it’s literally just a pointer to where it needs to be right so there it is primagen personal Mega Cort get work trees Ultra Corp so it’s saying where it’s located at pretty cool right I’ve been programming for 12 years and I like to think of get as magic under the hood it’s really it’s it’s it’s shockingly it’s not the most complicated piece of software I’m sure the actual operations for like creating and deleting files and stuff like that is complicated but everything else is uh like how it works is actually not like the most oh my gosh how could this possibly be right all right no duplicate branches linked work trees uh behave like normal get repos you can create branches switch branches delete branches create tags Etc but there is one thing you cannot do you cannot work on the branch that is currently checked out by another tree branch navigate to ultra Corp attempt to switch to main so when I try to switch out main it says already used right makes sense right yeah tracking so how does your main tree uh main working tree know about your linked working tree well the reference is stored in G work trees directory list the contents of this directory so if we go like this if we go to here and go uh ls- La get work trees this is a new one you’ll notice that Ultra Corp is right here so if I go in here you’ll notice that it has effectively the entirety of everything you need to know about it where its head is pointing it’s like a mini little it’s like a little mini git experiences going on right here here and even has a g dur and you’ll notice that the G dur if we look at it will actually be like the inversion of the other one whoopsies there we go oh my goodness how did I get that there we go it’s the path to where we’re going so that’s how it know it exists that’s why when I go work tree list it’s able to actually find this if I were to delete Ultra Corp it’ actually say like dead or prune or something like that removed I forget what it says but it says something how does the work tree keep track of it the main working let’s see the work Tre directory contains references to them yep Mega corpse IT staff manually logs it in Juro their project manager software actual magic which one is it all right when you make a change in a linked work tree the change is automatically reflected in the main work tree it makes sense the linked work tree doesn’t have a g directory so it’s not a separate repository it’s just a different view of the same repository you can almost think of a linked work tree as just another branch in the same repo but with its own space on the file system run get branch on your main work tree uh and answer the question so if I click this get Branch look at that you can even see the little plus sign right there that’s because it’s being checked out in a work tree it’s kind of fun thing uh how can you tell if a branch has checked out uh in a different work tree uh the branch will have no prefix that has a plus prefix let’s go plus prefix let’s go deleting work trees you may never need the stash again this is the nice part about working with work trees is you don’t actually ever need the stash ever again you can have two work trees that are always you know you can switch between them you can always check out a new one every time you work on a branch I had somebody at my old uh job tell me that stashing or switching branches is an anti- pattern you should just always work tree um anyways however at some point you need to clean up your work trees the simplest way was to remove the subcommand you can do a remove but you can also do something cooler which I actually prefer you can just delete the directory watch this one uh let’s see hold on does it say that remove alra Corp cool get uh rmrf backback alra Corp there we go so if I go get work tree list again you can see this right here see prunable I knew it said something I couldn’t remember the word it said but now that means if I go get work tree prune it’s able to tell what to prune because remember when we did this when we CED the gter ultra Corp had a directory so when it goes and it goes here it cats out this thing it stats that file when that file doesn’t exist then it knows that it doesn’t work that this thing has been detached what about npn modules you have that I mean you can copy you can create a script right I just I talked about that the whole environment part of work trees can be difficult right there we go bam I always had like two or three working trees and I would actually just switch between them so whenever I needed to do something I could actually just grab that and change it all right tags uh we’re going to wrap up this course with an easy one tags tags again I showed this at the very beginning of the course tags has the craziest user manual but it’s so simple to list all the tags you can just do get tag so get tag I have no tags very very easy tag is just an immutable pointer to a commit very very nice we can create a tag by just doing this tag a give it a tag name give it a message all of that all right create a tag on the latest commit p with the name candidate and a descriptive message all right get tag uh a see so we can go get tag- a if you want a name so the name can be candidate like that right and then you can do a message message such candid candidate boom get tag look at that beauty right there you can you can also if I’m not mistaken you can also create a uh tag without having to do this right there you go you don’t have to use a a it’s like the default first parameter there we go now tags remember you cannot edit a tag so when I check out a tag get check out tag let’s you get check out candidate I go into a detached head State like you can’t make edits to a tag tags are immutable pointers it’s very important to remember that and also one last thing get log one line you can also see uh tags when you have decorations which is nice why would one use a tag oh very very simple let’s go like this let’s go to uh GitHub uh react let’s just go check out the react Library let’s check out what tags they have tags do those look familiar if you’ve kept track at all react server components exist in 18 right people typically use tags to point to versions that are released in public so this is like a very normal Behavior Uh that you should see tags for they’re usually some sort of release uh now you can do stuff with sver this is typically how people do this with just sver it’s kind of weird to just name tags any old thing we’re developers we like structure sameness and sometimes even bike shedding I love bike Shing sver semantic versioning is a name and Convention by the way I’ve been bit so hard by sver because of this one right here minor sometimes it isn’t a safe feature if people change default parameters just so you know default parameters don’t technically break major versioning of sver and can screw you just so you know just in case you’re wondering note V isn’t actually a part of the sver correct major this means a change to the API in which will break compiling code minor means a an additive change to the API that won’t break a code patch means no change to the API at all there you go um that’s the easiest way to say it uh the sort let’s see to sort them from highest to lowest uh you first compare the major versions then a major minor versions then finally patch versions for example major version 2 is always greater than major version one regardless of the minor version absolutely if I’m using some code that’s on V1 124 and I see a new version 224 is available should I expect to be able to safely upgrade without making any changes to use it no major versions are not backwards compatible or typically are not major are not backwards compatible good thing to know you know what I mean good thing to know what’s the highest version 422 422 let’s go I’m so good at this I’m so good at this conventional tags um tags are used for all sorts of reasons but sometimes they’re used to uh to denote releases in that case tags follow the sver are common right here so tags this is very normal right fun fact pretty much anywhere you can use a commit hash you can use a tag uh name when working with Git right it’s a commit let’s see assignment add another tag to this let’s see to the same latest commit right commits going have multiple tags which we already did and then there we go boom uh get tag V 1.0.0 that’d be like oopsies that’d be like a normal one get push uh tags there we go push them all up let’s go got it tags okay guys stop making fun of my tags there we go we’re done I just did two git courses thank you very very much I hope you enjoyed this presentation of boot dodev GS course in which I helped create quite a bit the name is the primagen boot. deprime use it

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

  • The Muslim World’s Struggle for Identity

    The Muslim World’s Struggle for Identity

    The provided text is a collection of excerpts from a work exploring the complex identity and challenges faced by Muslims. It examines historical and contemporary issues, including religious practices, political conflicts, and the struggle to maintain cultural identity in a diverse and often hostile world. The writing reflects anxieties about minority status, cultural preservation, and the internal conflicts within the Muslim community. The author uses historical and religious references to illustrate these concerns, weaving together narratives, anecdotes, and reflections. Ultimately, the text advocates for a more unified and tolerant approach to Islam and its place in the world.

    Islamic Thought & Identity: A Study Guide

    Quiz

    Instructions: Answer each question in 2-3 sentences.

    1. According to the text, what is the significance of a mother’s death in the context of poverty and how does it compare to the status of Maulvi Mir Hasan?
    2. Explain how the text uses the concept of “tribe” and its associated deities in relation to various religious traditions.
    3. What is the central issue surrounding the “Nazar doctor” and his relationship with the individual who is presenting the issue?
    4. How does the text portray the relationship between the Prophet Muhammad and Mecca, and what is the significance of the Masjid-e-Haram in this context?
    5. Describe the tension presented in the text between the desire for Muslim unity and the reality of internal divisions and fears within the Muslim community.
    6. What is the author’s view on the role of religious fanatics and their impact on the perception of Islam?
    7. Explain the author’s assertion that “Muslims are neither getting destroyed nor are being thrown into the well” in the context of their political engagement in non-Muslim states.
    8. According to the text, what is the author’s view on maintaining one’s identity and how does it relate to the broader goal of human unity?
    9. What is the author’s position on the need for political activity and what is the connection to the history of religious communities?
    10. What is the central point the author is trying to make about the importance of humanism and unity?

    Quiz Answer Key

    1. The text suggests that a mother’s death due to poverty is a profoundly significant event, elevating her status above a figure like Maulvi Mir Hasan, whose mistakes are considered unforgivable. This highlights the immense value placed on motherhood and the impact of socio-economic hardship.
    2. The text uses “tribe” to connect ancient deities and religious practices, such as those of the Greeks, Egyptians, and Hindus, to the idea of distinct communal identities, similar to how the concept of God Israel is used in the Bible. This shows how different cultures have had their own ways of representing God, creating varied forms of religious devotion.
    3. The “Nazar doctor” is presented as someone with authority, possibly a leader or figure of importance, who is being challenged by a Muslim seeking recognition as an equal. The central conflict involves the tension between religious identity and human equality.
    4. The text suggests that the Prophet of Mecca stands above the history of the book and the Masjid-e-Haram, highlighting the central role of the Prophet and his teachings for Muslims. The Mosque acts as a symbol of religious community and identity, further establishing the historical significance of the city and Islam.
    5. The text highlights an internal conflict where the community desires unity and solidarity, but is hampered by internal fears, anxieties, and divisions, such as between sects. These divisions are an obstacle to a united Muslim identity, with these fears and conflicts becoming major issues.
    6. The author views religious fanatics as problematic, suggesting that their actions and narrow interpretations of Islam negatively impact the broader perception of the faith, creating further division and fear within the world. Fanatics are seen as a source of trouble for everyone, not just non-believers.
    7. The author argues that Muslims are navigating political landscapes in non-Muslim states effectively, achieving their goals, rather than facing destruction or persecution, suggesting a degree of resilience and agency in their political strategies within various states. They are also using non-Muslim states to their own benefit.
    8. While the author believes that maintaining one’s identity is important, it should not come at the expense of human unity. The text seeks a balance between individual identities and the collective goal of a shared humanity.
    9. The author argues that political action is acceptable if it is designed to promote human rights and freedoms and religious rights. The text points to the importance of maintaining and recognizing political rights for a religious community.
    10. The text advocates for a universalist view of humanity, emphasizing the importance of compassion, unity, and love for all people, regardless of religious or cultural background, positioning these virtues as the essence of Islamic thought and teachings.

    Essay Questions

    1. Analyze the complex relationship between religious identity and political engagement as portrayed in the text. How does the author navigate the tensions between maintaining Muslim identity and advocating for universal human rights?
    2. Explore the recurring theme of fear and anxiety within the Muslim community as described in the text. What are the sources of these fears, and how do they affect the community’s sense of identity and belonging?
    3. Discuss the author’s critique of religious fanaticism and its impact on the perception of Islam. How does the author propose balancing religious devotion with a commitment to humanism and tolerance?
    4. Examine the ways in which the text uses historical and religious figures and events to illustrate contemporary issues faced by Muslims. What are the key lessons and insights derived from these references?
    5. Evaluate the author’s perspective on the role of the individual in shaping their identity and the collective identity of the Muslim community. To what extent does the author emphasize personal responsibility and agency in addressing the challenges facing the Muslim world?

    Glossary of Key Terms

    Al-Kitab: (Arabic: الكتاب) Literally “the Book,” referring to the divine scriptures, often specifically the Quran in Islamic context, as is true in the provided text. It can also refer to scripture in general. Baitul Muqaddas: (Arabic: بيت المقدس) The Arabic name for Jerusalem, a city of significance to Muslims as well as other religious groups. Bani Saleel: A term used in the text, referencing people or a community that is not fully defined; it is a contested term used in the text that refers to people seen as an outgroup. Darvesh: A term used in the text referring to a person who is seen as a holy man. Dawat: The Arabic word for invitation. In the context of Islam, it often refers to the invitation to Islam or the call to faith. Geeta: Refers to the Bhagavad Geeta, a revered Hindu scripture. Gupta Nazar: A contested term in the text, the meaning is unclear, possibly referring to someone’s opinion or gaze as interpreted by a religious tradition. Haram: (Arabic: حرام) Forbidden or prohibited in Islam. Refers to actions, objects, or behaviors that are deemed impermissible according to Islamic law. Hijra: (Arabic: هجرة) The migration or journey of the Prophet Muhammad and his followers from Mecca to Medina in 622 CE, a pivotal event in Islamic history. Jamiat: A term used in the text, referring to a group or association of people; this is a common term, used in many contexts. Jihad: (Arabic: جهاد) The struggle or striving in the path of God. This can encompass personal, spiritual, and, in some contexts, military efforts. Kufri Dab: A contested term in the text that refers to something associated with not believing, perhaps an anti-Muslim sentiment. Mashriqi: A term used in the text, likely referring to an Oriental or Eastern person/influence in relation to the Prophet of Mecca. Masjid-e-Haram: (Arabic: المسجد الحرام) The Sacred Mosque in Mecca, Islam’s holiest site. Maulvi: A Muslim religious scholar or cleric. Medina: A city in Saudi Arabia, also known as Al-Madinah, where the Prophet Muhammad established the first Muslim community after migrating from Mecca. Mughal: Relating to the Mughal Empire that controlled most of India from the 16th to the 18th century. Mushabat: The text is likely referring to Mushabihat, meaning similarity or likeness in Arabic. Nazar: (Arabic: نظر) “Sight” or “gaze.” In some contexts, this can also relate to religious beliefs about the evil eye. Nawab: A term from India referring to a ruler or noble. Purvanchal: A geographical and cultural region located in Eastern India. Qibla: The direction of the Kaaba in Mecca, toward which Muslims turn in prayer. Quran: (Arabic: القرآن) The holy book of Islam, believed by Muslims to be the word of God as revealed to the Prophet Muhammad. Ras Mufti: A contested term in the text, likely referring to a leading religious or legal official. Shakush: A contested term in the text; this could relate to a challenge or personal issue in the context of religious and personal identity. Sharia: Islamic law derived from the Quran and the teachings of the Prophet Muhammad. Vedas: A collection of ancient Hindu scriptures. Yagya: A Hindu religious ritual that is often a sacrifice.

    Muslim Identity, Global Politics, and Internal Conflict

    Okay, here’s a detailed briefing document analyzing the provided text, focusing on key themes, ideas, and significant quotes:

    Briefing Document: Analysis of “Pasted Text”

    Introduction:

    This document analyzes a complex and at times fragmented text that appears to be a personal reflection on Islam, Muslim identity, and global politics, seemingly from the perspective of someone deeply invested in the issues but struggling with internal contradictions and external pressures. The text meanders through personal anecdotes, historical references, religious interpretations, and observations on contemporary events. The writing style is very informal and at times unclear, potentially due to translation or transcription issues.

    Main Themes and Ideas:

    1. Internal Conflict within Muslim Identity: A major theme is the internal struggle of Muslims attempting to reconcile their faith with modernity, political realities, and diverse cultural contexts. The author grapples with the challenges of maintaining Islamic identity while living in non-Muslim majority nations, expressing fear of cultural assimilation and the loss of tradition:
    • Quote: “Muslims of India are victims of severe anxiety and confusion with regard to the Muslim community. They are filled with fear every moment.”
    • Quote: “Most of the Muslims are sad from inside. They feel this pain deeply that their children are becoming Islamic. They are sad that even then the Islamic culture is not getting the status which it deserves in their eyes.”
    1. Critique of Religious Dogmatism and Fanaticism: The text critiques rigid interpretations of Islam and the actions of extremist groups, highlighting how they undermine the core values of the faith. This is juxtaposed with a longing for the unifying, humanistic aspects of Islam:
    • Quote: “Today, we are troubled by the strict religious fanatics. They have a complaint on their thoughts that Mohammed is less rich.”
    • Quote: “Today’s increasing human sugar level has reached to a minimum then this is a pocket of humanity… Without any compulsion or feeling of complaint…”
    • Quote: “The fight of Muslims with the bad festival is not justified, those who cite the demand or search of the Prophet for the lack of Hazrat, they are also the pride of human nature”
    1. Historical and Theological References: The author draws from Islamic history, scripture (Quran), and other religious traditions (Bible, Vedas) to contextualize their points. They emphasize that historical figures like the Prophet Muhammad were not above criticism and change, suggesting a more nuanced reading of religious texts:
    • Quote: “…we can see the document of this tanzar with both the wrestlers, whisky in Medina…”
    • Quote: “In the very last part of his Meccan life he wrote a great paper on such issues but it will be interesting to know about it when he compared his question on Mecca with the history of the book.”
    • Quote: “Just as we see mention of God Israel repeatedly in the Bible, similarly we can read about the racial gods and goddesses of the Greeks and Egyptians in their Deity and in Hinduism as well.”
    1. Global Politics and Muslim Persecution: The text frequently addresses the plight of Muslims in various conflict zones, attributing much of their suffering to political interference and Western powers, with particular emphasis on the role of the US:
    • Quote: “Their huge population is looted. In the three states of Kashmir, Chechnya and Bosnia, various types of Muslims have been kept with the Muslims. Whatever America is doing in Afghanistan, it is at the heart of it.”
    • Quote: “With the force of propaganda, Muslims are spreading the news in videos that which stories they consider as attacks and we are ready to debate on each name and every village.”
    1. The Importance of Humanism and Unity: There is a consistent call for a universal understanding of Islam that prioritizes humanism, tolerance, and unity among all people, transcending religious and cultural differences:
    • Quote: “The world is God’s family, and God only likes those who love his goons…”
    • Quote: “You are explaining in this way the tolerance of humanity…”
    • Quote: “humanity is the power of our religion… its invitation is not an invitation to inferiority but to humanity.”
    1. Fear of Marginalization and the “Other”: The author expresses concern over the rise of Islamophobia and the perception of Muslims as inherently separate or threatening. They are critical of the ways in which Muslim identity is often defined by external, often negative stereotypes:
    • Quote: “Sometimes a strange issue arises, sometimes the dress and beard and sometimes the symbols of Muslim are given to the Manro of the Masajat and the wait begins that our identity, story, blurred weakness should not be spoiled…”
    • Quote: “They complain that like other people, Muslims should also settle in Magra. Despite being benefited by all the Musabahs, they consider our society to be poor.”
    • Quote: “The truth is that Muslims in Magra Today people give Islamo phobia to the things…”
    1. Critique of Nation-State and Political Manipulation: There’s a questioning of the modern nation-state and its impact on Muslim identity. The text implies that the formation of Pakistan has created more problems than it has solved. It suggests that political machinations by both non-Muslim and Muslim actors have led to increased suffering for the Muslim population.
    • Quote: “The Muslims of India are victims of severe anxiety and confusion with regard to the Muslim community.”
    • Quote: “Today, Muslims all over the world who are living their lives in non-Muslim areas through the politics of their cities, are achieving the goals of non-Muslim states in the light of principles. Due to this, Muslims are neither getting destroyed nor are being thrown into the well.”
    • Quote: “They had come giving advice that they are not going to look at us as loyal citizens of their country Hindustan, but in the first or second year of Pakistan’s assembly, while putting up their list, they clearly declared in the book that now neither Hindus will stay here nor Muslims.”

    Key Observations and Interpretations

    • Fragmented Narrative: The text’s lack of structure and frequent shifts in subject make it difficult to follow a linear argument. It reads more like a stream of consciousness reflecting the author’s ongoing engagement with complex issues.
    • Personal Struggle: The personal and emotional tone indicates a deep internal struggle to reconcile religious belief, cultural identity, and observations of global conflict.
    • Call for Self-Reflection: Despite the criticism directed towards others, there is a strong element of self-reflection within the text, urging Muslims to introspect and reconsider their approach to their faith and their place in the world.
    • The Importance of Historical Understanding: The author emphasizes that a true understanding of Islam requires a deep engagement with its history and context rather than just a superficial reading of religious texts.
    • Emphasis on Human Equality: Ultimately, the message seems to be a plea for recognizing the common humanity of all people, regardless of their religious or cultural backgrounds.

    Conclusion:

    This document indicates the complexities involved in understanding the Muslim experience in today’s world. The author’s perspective reveals the intense inner struggle of identity, and the external pressure of global politics and cultural misunderstandings. The document does not provide easy answers but serves as a valuable lens through which to observe the contemporary challenges of Islamic faith in the 21st century.

    This briefing document should provide a thorough overview of the main themes and ideas present in your text. Let me know if you would like further clarification on any point.

    Muslim Identity in a Complex World

    FAQ: Key Themes and Ideas

    1. What is the central conflict or tension explored in this text regarding Muslim identity?
    2. The text grapples with the internal conflict of Muslims navigating their identity in a complex world. It highlights tensions between maintaining religious and cultural traditions, while also participating in modern society. There is a struggle between the desire to maintain a distinct Muslim identity (e.g. through dress, practices) and the fear of that identity being marginalized or attacked, both internally by fanatical elements and externally by other groups. This conflict is exacerbated by a sense of being both a minority in some places and a majority in others, and the corresponding pressures and anxieties that arise from both positions. There is a consistent fear that Muslim identity will be “spoiled” or lost, whether through external forces, internal divisions or modernization. The text also addresses the tension between a more universal humanitarian vision and a more insular, particularist approach.
    3. How does the text portray the relationship between Islam and politics?
    4. The text presents a conflicted view of the relationship between Islam and politics. There is an acknowledgement that political forces have historically shaped the Muslim world, and that Muslims are engaging with politics in both Muslim-majority and minority countries. However, the text also seems critical of attempts to impose a singular political vision on all Muslims, stressing that a person’s political engagement is not a measure of their faith or their commitment to Islam. The text suggests that Muslims should focus on a wider sense of community and humanity, rather than adhering to strict political identities. A strong distinction is made between the need for political agency and the pitfalls of a singular political identity that can lead to division and conflict. The text questions the relevance of old political models like the Caliphate and seems to support an individual right to political expression even while stressing a universal identity.
    5. What does the text say about the role of tradition versus modernity in Muslim life?
    6. The text is deeply concerned with the relationship between tradition and modernity, and it doesn’t offer a simple answer. There is a clear appreciation of traditional practices and the deep history of Islamic civilization, but also an awareness that many things have changed. The text acknowledges the impact of modernization on Muslim societies and cultures around the world and sees that modernity poses challenges, such as cultural assimilation, loss of identity, and a fear that new generations are losing their connection to Islam, but also opportunities. The text does not condemn modernization, however, but rather encourages Muslims to engage with it in a way that honors their values and does not lead to intolerance.
    7. How does the text address the issue of religious diversity and tolerance?
    8. The text advocates for a more inclusive and tolerant view of religious diversity. While it acknowledges the importance of Islam to Muslims, it also highlights a universal notion of humanity where all people are seen as deserving of respect and dignity, and even as part of the same extended family. It criticizes those who use religion to justify hatred, oppression, or division, and promotes the idea that the core message of Islam is one of unity and humanity. The text also points to historical examples of tolerance and religious coexistence. The text sees the true essence of Islam as a message of human unity, tolerance and compassion. The text recognizes that conflict may exist between various groups, but that this conflict is not a function of religious differences alone but of political and power dynamics.
    9. What does the text suggest about the fears and anxieties faced by Muslims today?
    10. The text paints a vivid picture of the fears and anxieties that many Muslims experience today. These include the fear of oppression, violence, and discrimination, both in Muslim-majority and minority contexts, and an internal fear of losing their identity. There is anxiety about a perceived decline of Islamic culture, the influence of the outside world on the youth, and a concern about the internal conflicts that divide the community. The text points to the emotional toll these fears take on individuals and the need for Muslims to find inner peace and stability. The fear of “group phobia”, is identified as a key source of concern. These fears are shown to be related to both external aggression and internal conflict.
    11. How does the text define the relationship between individual identity and communal identity?
    12. The text presents a complex interplay between individual identity and communal identity. It emphasizes the importance of Muslims maintaining their distinct cultural and religious identity while also urging them not to lose sight of their shared humanity and their universal connection. It encourages individuals to have the freedom to express themselves without compromising the communal values and the need for tolerance and mutual respect. The text recognizes the importance of belonging to a group, but also stresses that individual agency should not be suppressed. It highlights that the group identity should be one of peace and progress and not one of hatred and conflict. A person should be able to be both Muslim and a citizen of the world and to contribute to society at large while maintaining their values.
    13. What is the significance of references to historical figures and events in the text?
    14. Historical figures like Prophet Muhammad, Moses, and Mughal emperors, and historical events such as the Hijra, Mecca’s history, are used to illustrate key arguments. These references serve several purposes. They provide a sense of historical context, grounding the current struggles in a longer narrative. They also offer examples of how Muslims have navigated difficult times in the past, emphasizing the endurance of their faith. By comparing current events to historical precedent, the author seems to encourage a thoughtful approach to resolving the internal and external issues Muslims face. By using both shared Islamic figures and examples from other groups, the text is stressing both the uniqueness of Islamic experience and the importance of a broader, human history. The text seems to be invoking historical references as a means of both grounding Muslims in their tradition while also encouraging adaptability and universalism.
    15. What overall message does the text seem to be trying to convey?
    16. The text conveys a message calling for a renewed understanding of Muslim identity rooted in both cultural heritage and universal human values. It advocates for a path that embraces tradition while also engaging with the modern world, emphasizing the importance of tolerance, compassion, and unity. It calls for Muslims to address their internal conflicts, to overcome their fears, and to recognize their shared humanity with all people. The text encourages a dynamic approach to faith that promotes a deep and thoughtful engagement with the world rather than a retreat into narrow and divisive identities. It also stresses that faith should serve humanity and lead to constructive actions. The message is one of hope and progress and not division and hatred.

    Islamic Identity in a Changing World

    Okay, here is a timeline of events and a cast of characters based on the provided text, which is quite dense and at times, difficult to parse due to its unusual phrasing and structure. I have done my best to extract what seems to be the most relevant information.

    Timeline of Main Events:

    • Early Period (Implied, not explicitly dated):
    • References to historical figures and events such as:
    • Biblical figures: Moses and Israel
    • Greek and Egyptian deities, and Hindu scriptures (Geeta and Vedas).
    • Mecca and the idols Latnath and Hubble.
    • The Prophet Moses and Medina
    • The Prophet of Mecca
    • Discussion of the concept of racial gods and goddesses.
    • Mention of early Islamic figures and practices, including the Hijra.
    • Debate about the call to prayer (adhan).
    • The establishment of a new “Tariq Tanzeem Yajmat” with a separate identity.
    • The Prophet Muhammad’s time in Medina and his interactions with the community.
    • Later Period (Also implied, but more recent, with contemporary references):
    • Concerns about the identity of Muslims in the modern world.
    • Fears about the oppression and marginalization of Muslims in various places.
    • Mention of India and Pakistan, suggesting a post-partition context.
    • References to Kashmir, Chechnya and Bosnia.
    • Mention of Afghanistan
    • Anxiety regarding the loss of Islamic culture and identity among Muslim youth in Western countries.
    • Concern about the influence of Western culture and materialism on Muslim communities.
    • Discussion of conflicts in the world and debates about terrorism.
    • References to contemporary issues such as national identity, and the need for unity within the Muslim community.
    • Debate about the relationship between Islam and politics.
    • Arguments for a balance between maintaining religious identity and engaging with broader society.
    • Discussions about the nature of humanity and tolerance.
    • The notion of God’s family and all humans as children of God.

    Cast of Characters and Brief Bios:

    • Afzal Rehan Azam: Mentioned in the opening as someone whose impact is described as an “Islamic poem”. The tone suggests a figure respected within the community.
    • Mother Respected Doctor Khalid Masood: A mother held in high regard because of her poverty, contrasting with the respect accorded to religious figures like Maulvi Mir Hasan.
    • Maulvi Mir Hasan: A religious figure whose actions are deemed “haram” (forbidden) by the author, who sees the actions of Mother Respected Doctor Khalid Masood as more virtuous
    • Kaushal: Someone who brings “sushimara of the hand of Allah.” Mentioned also as being Gujarati.
    • Darvesh: A person grateful to “doctor sahib” (possibly Dr. Khalid Masood) for an opportunity to see Nasir in the Vedas.
    • Nasir: Someone who Darvesh is grateful to have had the opportunity to see in the Vedas.
    • Qibla (doctor sahib): A respected figure who states that Muslims are Islamic by his reference and who is treated with great respect
    • Gupta Nazar: An unspecified popular topic associated with the “Nazar doctor.”
    • Evelyn Mukadhin Sardarni Qureshi: A woman who is named as going to Mecca with someone else who is trying to face his “Tashkush”. In the text, there is also mention of her authorization of the freedom of religion.
    • Prophet Moses: A key religious figure from the Bible, often mentioned in comparison to the Prophet Muhammad.
    • Prophet Muhammad: The central figure of Islam, referred to frequently in various contexts and situations.
    • Umar Farooq: A well-read friend of the author whose learning inspires him.
    • Ikhthar: Someone who is described as being afraid.
    • Fahd: A person linked with having an opportunity for insurance.
    • Syed: A person who claims to be on a mission to kill a member of “Bani Saleel.” Also linked to Medina under the Seerat of Musa.
    • Pol Rasool: A person who opened the opinion of recognizing “Kalam of Dawat”.
    • Nawab of Ruhal Kuchh: A person that Pol Rasool has a mission to make.
    • Ibrahim: A relative of the author through a relation company, who is also described as an brother of Moses Arun and Mohammed.
    • Moses Arun: Brother of the author through a relation company, who is also described as a brother of Ibrahim and Mohammed.
    • Mohammed (Shakas): Brother of the author through a relation company, who is also described as a brother of Ibrahim and Moses Arun.
    • Salamat Sheikh: Someone who should not say bad things, although the minority has its own Muslims in the Jamiat.
    • Manro of the Masajat: The symbol of the Muslim identity, which people begin to worry about its “blurred weakness”
    • Chandravesh: Someone who is called “Malik Nimki Kashish”.
    • Siddhartha: Possibly refers to Siddhartha Gautama (Buddha), with an implication that there is an analogy between the Siddhartha treaty and terrorism.
    • Bin Safia and the tribes: Group that is described as powerful Turks and that the Americans have kept the Muslims at bay from.
    • Ras Mufti’s mother: A woman whose vision and action are enjoyed by Muslims.
    • Nazia: Someone whose invitation should be used to attack the whole world,
    • Rasul: Someone whose belief in the “pure” is what is desired by the narrator.
    • John: Someone who is not being allowed to “sit below anyone”
    • Didi: A person in the text who has “ground under”, that others want to put pressure on and destroy.
    • Purvanchal: Place that has a universal identity.
    • Karan: Person with a type of salty phobia (group phobia).
    • Tahir Raj Tarana: A person who tells about the news that has been taken from Sari to Magra.
    • Sandeep and Babli: People who should not consider themselves higher than others.
    • Hazrat: Someone that the text complains has become three times more popular in society.
    • Taskin: A person who is described as “humble” with a beneficial identity in the world, with their opinion about Congress being proven wrong.
    • Comyat/Shariat: Concepts linked to the foundations of Allah.
    • Komal Surya Hashmi: Person described as special who has kept the scope of different political hopes with reference to Pakistan. Also described as a nachadi foundation.
    • Harshad: Person whose caste is being used as a personal matter.
    • Ashrafiya: An establishment that meant a different country and was refused to adopt the political community.
    • Musa: A prophet who is the subject of debate regarding what has been said under the “Seerat” of Medina.
    • Abu Rera: Described as a Comrade who is surprised by the format that the officer has.
    • Ahmed Unnao: Person associated with immense emotions and having his “challan registered” in his name.
    • Saknath: Someone for whom emotions should be felt.
    • Aladdin: People who may not be the best representatives of the world’s mosques.

    Note:

    The text is very dense and uses a unique style, making it difficult to ascertain precise meanings or definite connections between events and people. The timeline and bios are based on the most plausible interpretations of the text. The text appears to be a combination of historical references, personal reflections, and social commentary, with a strong focus on Muslim identity in the modern world. The author seems to grapple with issues of religious purity, cultural preservation, and the political realities faced by Muslim communities.

    Let me know if you have any further questions.

    Muslim Identity: A Multifaceted Exploration

    Muslim identity is discussed from various angles in the sources, encompassing religious, cultural, and political aspects, as well as the challenges and fears faced by Muslims in different contexts [1-5].

    Religious Identity:

    • The sources touch on the core beliefs of Islam, including the concept of one God and the importance of the Quran [1, 6, 7].
    • There’s a focus on the figure of the Prophet Muhammad and his teachings [2, 6, 7].
    • The sources also discuss the significance of practices like prayer (Namaz), fasting during Moharram, and the call to prayer from the mosque [1, 6, 7].
    • Some sources contrast the idea of a universal Islamic identity with specific cultural and ethnic expressions of Islam [1, 2, 4].

    Cultural Identity:

    • Muslim identity is sometimes expressed through cultural symbols such as dress and beards [3].
    • There are references to Muslim civilization and its contributions to the world [5].
    • The sources also show how Muslim identity can be tied to specific places, such as Mecca and Medina, or to particular historical figures and events [6, 7].

    Political Identity:

    • The sources describe a tension between religious identity and political realities [2-4, 8].
    • There’s a discussion of the challenges faced by Muslims as minorities in various countries, including fear of oppression [2, 3].
    • The text also mentions how Muslims are impacted by political conflicts and power dynamics [3, 4].
    • Some sources argue for the importance of Muslim unity and solidarity in the face of adversity and injustice [4, 9].

    Challenges and Fears:

    • The sources highlight the anxieties and fears of Muslims in various parts of the world, including India [2, 5].
    • There are concerns about the erosion of Muslim identity and culture in the face of global influences [3, 5].
    • Some sources mention the issue of Islamophobia and the misrepresentation of Muslims in the media [3, 5].
    • The texts also discuss how Muslims grapple with internal conflicts and differences within the community [2, 3, 5].

    Diverse Perspectives:

    • It is noted that Muslims have diverse opinions and that not all Muslims share the same agenda or viewpoints [2, 3].
    • There is an acknowledgement of different interpretations of Islamic teachings and practices [1, 6, 7].
    • Some sources suggest that Muslims should focus on their own welfare without harming others [3].
    • The sources also convey the idea that Muslim identity can be shaped by both religious principles and political circumstances [4, 8].

    Internal Conflicts:

    • There are references to internal divisions within the Muslim community, including the conflict between Sunnis and Shias, as well as the tensions between different cultural and ethnic groups [1, 3, 10].

    Universality:

    • The sources also express an idea of a universal human identity, where all people are considered children of God, regardless of their religion or background. [9]
    • Some sources argue that Muslims should focus on common goals with other people [9, 10].

    The sources emphasize that Muslim identity is a complex and multifaceted concept, influenced by religion, culture, politics, history, and personal experience [1-11].

    Religious Tolerance: Ideals and Challenges

    Religious tolerance is discussed in the sources, with varied perspectives on its practice and importance.

    Acceptance of other faiths:

    • One source describes a historical instance where the religious and ideological freedom of Prophet Islam and his followers was accepted, including the right to choose a new religion [1].
    • The sources also mention a concept that all human beings are children of God and worthy of respect [2]. This implies a universalistic view that values all people, irrespective of their faith.
    • There is also a statement that any thing related to goodness or courage is something that Muslims should embrace, wherever it is found, suggesting a tolerance towards other cultures and traditions [2].

    Challenges to religious tolerance:

    • Some sources mention the fear and anxiety of Muslims in the face of oppression [3], which can be a barrier to tolerance between groups.
    • There are references to a “strict religious fanatics” [3], which suggests that some individuals and groups are not tolerant of other faiths.
    • The sources note that some groups believe that other marriages apart from their own are “infidels” [4]. This indicates a lack of tolerance for those outside of their own group.
    • The sources also mention the existence of a group phobia, which also relates to a lack of acceptance of those outside one’s group [5].
    • Some sources note the desire of some to impose their religious views [4], which is contrary to the idea of tolerance.
    • There is also mention of hatred and doubt, which can be barriers to religious tolerance [3].
    • Some sources express concern about the loss of Islamic culture and identity in the face of outside influences, suggesting a possible struggle with tolerating differing cultural and religious norms [5].

    Arguments for religious tolerance:

    • One source suggests that Muslims should focus on their own welfare without harming others [6]. This suggests a principle of non-interference in the affairs of other religious groups.
    • The sources indicate that the purpose of religion is to invite humanity towards unity and brotherhood [7], which suggests that tolerance is essential to the proper practice of religion.
    • There is the idea that one should not hate the children or family members of someone that one loves, suggesting that tolerance should extend to those of other faiths [2].
    • One source indicates that the fight of Muslims should not be against the bad festivals of other groups [1].
    • Some sources express that the “whole world is God’s family” and one should love all of God’s people, suggesting that religious tolerance is a key principle [2].
    • It is argued that, by freeing themselves from the “shackles of slavery”, people can adopt the thinking of human welfare [2].
    • There is also a suggestion that the preachers of unity have raised their voices against those who have turned their back on humanity and fought against them [2].

    Internal divisions:

    • The sources also discuss internal divisions within the Muslim community [5, 6], which are not necessarily related to religious tolerance, but do reflect a lack of acceptance of different views and beliefs within their own group.

    In conclusion, the sources reveal a complex picture of religious tolerance. While they provide examples and arguments for acceptance, they also highlight the challenges and barriers to achieving it. The sources suggest that religious tolerance is both an ideal to strive for and a practical necessity for building a peaceful and harmonious world.

    Muslim Cultural Preservation in a Changing World

    Cultural preservation is discussed in the sources, mainly in the context of Muslim identity and the challenges it faces in a changing world. The sources reveal a concern for maintaining cultural traditions and values in the face of both internal and external pressures [1].

    Key aspects of cultural preservation discussed in the sources:

    • Maintaining Identity: The sources show that there is a strong desire to maintain a distinct cultural identity [1-3]. This includes things like religious practices, traditions, and values that are unique to Muslim culture [1]. There is a fear that the loss of cultural identity will lead to a loss of distinctiveness [4, 5].
    • Resistance to Change: Some of the sources suggest that some Muslims are resistant to change and want to preserve their traditions [1, 4]. This resistance may be driven by a fear of losing their identity, or by a desire to maintain their unique way of life [4]. The sources mention concern about the influence of Western cultures and a desire to prevent their children from adopting non-Islamic lifestyles [1].
    • Cultural Symbols: Cultural preservation also involves maintaining cultural symbols, such as dress and beards [5]. The sources note that these symbols can be very important to people’s sense of identity and their desire to be part of a community [5].
    • Transmission to Future Generations: The sources express concern over the fact that some Muslim children are growing up in western countries and may not be adopting traditional Islamic culture [1]. There is a feeling of pain when it seems that Islamic culture is not getting the status it deserves [1].
    • Balancing Tradition and Modernity: The sources suggest that there is a tension between the desire to preserve traditional culture and the need to adapt to modern life [2, 4-6]. Some sources suggest that Muslims should focus on their own welfare without harming others [5, 7]. There is also a recognition that one must keep the best in the need of society [8].
    • Internal Diversity: It is important to note that the sources suggest that there are diverse opinions within the Muslim community regarding cultural preservation [1, 4, 5, 7]. Some may believe that preserving traditional culture is essential, while others may see a need for change and adaptation [4, 7]. There are references to the problems that stem from “strict religious fanatics” [4].
    • Universality vs. Specificity: While there is a desire to preserve Muslim identity, there are also ideas about universal values and the idea that all people are children of God [7]. Some sources suggest that Muslims should focus on common goals with other people [7].
    • Fear of Loss: The sources highlight the fear of losing their Maxus [5], a fear that can drive cultural preservation efforts. There is a fear of the end of their story and a blurred weakness [5]. This fear may be a result of living in areas with non-Muslim majorities or feeling that their culture is under attack by the outside world [4].

    In summary, the sources suggest that cultural preservation is a complex issue for Muslims, involving a desire to maintain their unique identity, transmit their values and traditions to future generations, and adapt to the challenges of a changing world. The sources underscore the tension between tradition and modernity, and the need for Muslims to navigate these challenges while staying true to their core values.

    Muslim Political Identity: A Global Perspective

    Political identity is a recurring theme in the sources, often intertwined with religious and cultural identity. The sources reveal a complex picture of how Muslims navigate the political landscape, both within their communities and in relation to the wider world.

    Key aspects of political identity discussed in the sources:

    • Minority Status and Fear: The sources emphasize that Muslims often live as minorities in various countries [1, 2]. This minority status is associated with a pervasive fear of oppression, anxiety, and confusion [1]. There is a sense that Muslims are constantly under threat and need to be vigilant in protecting their rights and interests [1, 3]. The sources also highlight the fear of the Hindu majority in Pakistan and the oppression of Muslims by other groups in the world [1].
    • Political Participation and Representation: The sources touch on the issue of Muslim political participation and representation in various contexts [2]. There is a sense that Muslims are often marginalized and excluded from political power [2]. The sources suggest that some Muslims feel they are not treated as loyal citizens in their countries [2]. However, some sources note that Muslims are achieving their goals in non-Muslim states through the politics of their cities [2].
    • The Desire for a Separate Political Identity: Some of the sources suggest that there is a desire among some Muslims for a separate and independent political state [2, 4]. This desire is often rooted in a sense of religious and cultural distinctiveness, as well as a desire to be free from oppression and persecution. This desire is tied to the idea that Muslims should have their own political community, or Ummah [4]. The sources mention that some Muslims had declared their political community, which was not only for Muslims but also for Hindus [2].
    • Political Strategy: The sources present the idea that Muslims may adopt different political strategies to achieve their goals [4]. Some may focus on working within existing political systems, while others may advocate for more radical forms of political action. For example, some Muslims may try to establish their own political organizations, while others may try to influence the policies of existing governments [2]. The sources mention that some Muslims are involved in debates about how to call people to the mosque and how to maintain their identity [5].
    • Impact of Geopolitics: The sources discuss the impact of global political dynamics on Muslim identity [6]. For example, they note that the actions of powerful countries such as the US in Afghanistan have a direct effect on the Muslim population [3]. The sources describe how some Muslims see the world as a battleground between different powers, with Muslims caught in the middle [6, 7]. The sources also discuss the impact of propaganda and media on how Muslims are perceived and how they see themselves [6].
    • The Tension Between Religious and Political Goals: The sources highlight the tension between religious and political goals [2]. There is a question of whether Muslims should focus primarily on their religious identity or whether they should engage in political action to advance their interests [2]. There is also a discussion of whether political aims should be prioritized over religious principles, and how Muslims should balance these two goals. Some sources suggest that Muslims should focus on their own welfare without harming others, while others argue that they need to fight for justice and liberation [3].
    • Internal Conflicts: The sources reveal internal divisions within the Muslim community [1]. These divisions can affect their political identity. For example, some Muslims may prioritize loyalty to their country, while others may identify more strongly with their religious community. There is a concern that some Muslims are so worried about their own community that they neglect the welfare of others [3].

    The Sources suggest that Muslim political identity is complex and multifaceted, shaped by a number of factors. These include religious beliefs, cultural values, historical experiences, and current political realities. The sources reveal the challenges that Muslims face in navigating these complexities, both within their communities and in the wider world. The sources also indicate that Muslims must balance their desire for religious and cultural preservation with the need to engage effectively in the political sphere.

    In conclusion, the sources reveal that political identity is a key concern for Muslims around the world, and is inextricably linked to their religious, cultural, and social identities. The sources emphasize that this political identity is not static or monolithic, but is rather a dynamic and contested space that is shaped by a variety of factors.

    Global Islam: Identity, Challenges, and Transformation

    Global Islam is discussed throughout the sources, though not always explicitly, and often as it relates to identity, tolerance, cultural preservation, and political action. The sources present a complex picture of a diverse global community with shared beliefs and values that is also facing a variety of challenges.

    Key aspects of Global Islam discussed in the sources:

    • Shared Religious Beliefs and Practices: The sources suggest a common foundation of Islamic beliefs and practices that unite Muslims worldwide. References to the Quran, the Prophet Muhammad, and practices such as prayer indicate a shared religious framework [1-3]. The sources also indicate a shared history and a common heritage, referencing historical figures and events [2].
    • Global Community (Ummah): The sources suggest a concept of a global Muslim community (Ummah) that transcends national boundaries [4]. This is reflected in statements about the unity of Muslims, the idea that all Muslims are brothers and sisters, and that they should support each other [5]. The sources reveal that some Muslims prioritize loyalty to their religious community over their national identity [6].
    • Cultural Identity: The sources describe a desire to preserve a distinct Muslim cultural identity, which is felt by Muslims all over the world [7, 8]. The sources express concern that the Muslim culture is not getting the status it deserves and that this culture is being lost to outside influences [8]. The sources also describe a desire to maintain cultural symbols such as dress and beards [7].
    • Minority Status and Challenges: The sources reveal that Muslims often live as minorities in various countries. This minority status is associated with a fear of oppression, anxiety, and confusion [9]. The sources highlight the fear of the Hindu majority in Pakistan and the oppression of Muslims by other groups in the world [6, 9]. They also express concern about the loss of Islamic culture and identity in the face of outside influences [8].
    • Political Engagement: The sources discuss how Muslims engage with the political landscape in various contexts. There is a sense that Muslims are often marginalized and excluded from political power [6]. Some Muslims may focus on working within existing political systems, while others may advocate for more radical forms of political action [4].
    • Internal Divisions: The sources acknowledge the existence of internal divisions within the Muslim community [1, 9]. These divisions can be based on differences in religious interpretation, political views, or cultural practices. This implies a lack of a monolithic global Muslim identity, and suggests a range of different perspectives within the community.
    • Tension Between Tradition and Modernity: The sources highlight a tension between the desire to preserve traditional culture and the need to adapt to modern life [8]. Some Muslims may be resistant to change and want to maintain their unique way of life, while others may see a need for change and adaptation [7]. The sources suggest a need to balance these two needs [4, 8].
    • Impact of Geopolitics: The sources discuss the impact of global political dynamics on Muslim identity [7]. Actions of powerful countries such as the US in Afghanistan have a direct effect on Muslim populations [7]. The sources describe how some Muslims see the world as a battleground between different powers, with Muslims caught in the middle [10].
    • Universal Values: Despite the focus on a distinct Muslim identity, the sources also express universal values, such as the idea that all people are children of God and are worthy of respect [5, 11]. This suggests a tension between a particular religious identity and a shared humanity. The sources indicate that the purpose of religion is to invite humanity towards unity and brotherhood, suggesting that tolerance is essential to the proper practice of religion [5].
    • Fear and Anxiety: The sources indicate that Muslims around the world are facing an increase in fear, anxiety, and confusion [7-9]. This may be due to increased discrimination, political unrest, and cultural misunderstandings. The sources suggest that this anxiety is felt by Muslims both in Muslim and non-Muslim majority countries [9].

    In conclusion, the sources portray Global Islam as a complex and multifaceted phenomenon. It is characterized by a shared religious foundation and a sense of community that transcends national boundaries. At the same time, the global Muslim community is diverse, faces many challenges, and is constantly evolving in response to changing social, political, and cultural realities. The sources suggest that Global Islam is both a unifying force and a site of internal tension, a dynamic space where Muslims navigate complex issues of identity, belonging, and the search for meaning in an increasingly interconnected world.

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

  • Al Riyadh Newspaper, March 5, 2025 Foreign Relations, Aid to Lebanon, Global Economic Concerns

    Al Riyadh Newspaper, March 5, 2025 Foreign Relations, Aid to Lebanon, Global Economic Concerns

    These articles from the Al Riyadh newspaper cover a range of topics including Saudi Arabia’s foreign relations and aid to Lebanon, its steadfast support for Palestine, and Crown Prince Mohammed bin Salman’s diplomatic activities. They also report on global economic concerns affecting stock markets and OPEC+ oil production, alongside domestic Saudi news such as the King Salman Prize for Quran حفظ, Ramadan استقبالات, and development projects. Additionally, the paper features local community initiatives during Ramadan, sports news covering football leagues and international competitions, and health and cultural events, providing a diverse snapshot of current affairs.

    Study Guide: Analysis of Al-Riyadh Newspaper Excerpts (March 5, 2025)

    Overview of Key Themes

    The provided excerpts from the Al-Riyadh newspaper published on Wednesday, March 5, 2025 (Rabi’ al-Awwal 15, 1446 AH) cover a range of domestic, regional, and international news and commentary relevant to Saudi Arabia. Key themes include:

    • Domestic Governance and Policy: Statements from the Crown Prince regarding the Kingdom’s commitment to serving pilgrims and supporting social services, cabinet approvals for initiatives like investment promotion and heritage mosque restoration, and regional development projects.
    • Foreign Policy and Regional Relations: Saudi Arabia’s stance on the Palestinian issue, its role in supporting Lebanon, its participation in Arab summits, and its perspective on the Sudanese conflict.
    • Economic News: Fluctuations in gold prices, a decrease in used car prices in Saudi Arabia, stable vegetable and fruit prices during Ramadan, and financial results of Saudi Aramco.
    • Social and Religious Affairs: Preparations for Ramadan in the Two Holy Mosques, initiatives to provide services to pilgrims, Ramadan-related social customs (collective Iftar), and the King Salman Award for memorizing the Quran.
    • Cultural and Heritage Preservation: The unveiling of the Islamic Arts Biennale in Jeddah showcasing historical artifacts, and the ongoing project to restore historical mosques.
    • International Issues: The ongoing conflict in Gaza, the humanitarian crisis and sexual violence in Sudan, and international economic developments like US-China trade tensions.
    • Health and Social Initiatives: Health awareness campaigns during Ramadan.
    • Commentary and Opinion: An article on the importance of sustainable social solidarity beyond seasonal charity.

    Key Concepts and Topics to Review

    • Saudi Arabia’s Vision 2030: Understand how the reported initiatives and policies align with the Kingdom’s long-term goals.
    • The Role of the Crown Prince and Council of Ministers: Recognize their functions in setting national priorities and approving policies.
    • Saudi Arabia’s Foreign Policy Principles: Identify the consistent themes in its approach to regional conflicts and international issues (e.g., support for Palestine, territorial integrity of nations, peaceful resolutions).
    • The Significance of the Two Holy Mosques: Understand the continuous efforts to enhance services and facilities for pilgrims, especially during peak seasons like Ramadan.
    • Economic Indicators: Note the trends in key sectors like automotive and commodities.
    • Cultural Preservation Efforts: Appreciate the initiatives aimed at safeguarding Saudi Arabia’s Islamic and national heritage.
    • The Impact of Regional Conflicts: Analyze Saudi Arabia’s involvement and stated positions on conflicts in Palestine, Lebanon, and Sudan.
    • The Importance of Ramadan: Recognize its significance in religious, social, and economic contexts within Saudi Arabia.
    • Humanitarian Issues: Understand the Kingdom’s response and concerns regarding humanitarian crises in the region.

    Quiz: Short-Answer Questions

    1. According to the Crown Prince’s statement, what are the two key areas the Saudi Arabian government remains committed to supporting?
    2. What was the main concern expressed by the Saudi Council of Ministers regarding the situation in the Palestinian territories? What did they urge the international community to do?
    3. What kind of aid has Saudi Arabia been providing to Lebanon, and what is the overarching vision for the relationship between the two countries?
    4. What was the key message delivered by the Saudi Minister of Foreign Affairs at the extraordinary Arab Summit held in Egypt?
    5. What are the primary factors contributing to the recent decrease in the prices of used cars in Saudi Arabia?
    6. Describe two specific initiatives undertaken in the Two Holy Mosques to enhance the experience of pilgrims during Ramadan.
    7. What is the objective of the project to develop historical mosques in Saudi Arabia, and what are some of the features being preserved?
    8. What is the “Peace Arab Initiative” mentioned in the context of Saudi Arabia’s policy towards the Palestinian issue, and when was it adopted?
    9. What is Saudi Arabia’s stated position regarding the ongoing conflict in Sudan, as reflected in the Foreign Ministry’s statement?
    10. What is the main argument presented in the opinion piece regarding social solidarity during Ramadan and beyond?

    Quiz Answer Key

    1. The Crown Prince stated the Saudi Arabian government remains committed to serving the guests of God (pilgrims) and continuing to support the system of social services.
    2. The Council expressed strong condemnation of the Israeli government’s decision to prevent the entry of humanitarian aid into the Gaza Strip. They urged the international community to uphold its responsibilities, activate international accountability mechanisms, and ensure sustained aid access.
    3. Saudi Arabia has been sending humanitarian aid to Lebanon via an air bridge, including food, relief, shelter, and medical supplies. The vision for the future is a “partnership era” with strengthened Arab relations, with the joint Saudi-Lebanese statement emphasizing cooperation on important issues.
    4. The Minister of Foreign Affairs, representing the Crown Prince, conveyed the greetings of the Custodian of the Two Holy Mosques and reiterated Saudi Arabia’s unwavering support for the Palestinian people’s right to establish their independent state on the 1967 borders with East Jerusalem as its capital.
    5. The primary factors include an increase in the supply of used cars in the market due to the availability of new models and regulatory measures taken by the Ministry of Commerce that helped to lower prices. Additionally, allowing the import of used cars has increased competition.
    6. Two initiatives include the experimental launch of “Al-Tahallul from Nusuk” service using mobile carts within the Haram to serve pilgrims and the development of a baggage storage service with electronic tracking and six designated locations.
    7. The objective is to rehabilitate and restore historical mosques for worship and prayer, preserving their original architectural authenticity and highlighting their cultural and historical dimension for the Kingdom. Features being preserved include the traditional Najdi architectural style, such as roofs made of mud, wood, and palm fronds.
    8. The “Peace Arab Initiative” is a vision presented by Saudi Arabia at the Beirut Arab Summit in March 2002, which was adopted by Arab leaders. It aims for a comprehensive and just peace in the Middle East.
    9. Saudi Arabia expressed its rejection of any illegitimate steps or measures taken outside the framework of Sudan’s official institutions that could undermine its unity or disregard the will of its people, including calls for forming a parallel government. It reiterated its support for Sudan’s security, stability, and territorial integrity and called on Sudanese parties to prioritize Sudan’s interests.
    10. The opinion piece argues that social solidarity should extend beyond seasonal charity during Ramadan to become a sustainable effort focused on empowering those in need, providing opportunities, and improving the quality of life through partnerships and initiatives that create lasting impact.

    Essay Format Questions

    1. Analyze the interconnectedness between Saudi Arabia’s domestic policies (as reflected in the cabinet decisions and development projects mentioned) and its regional foreign policy objectives in the Middle East.
    2. Discuss the multifaceted significance of Ramadan as portrayed in the newspaper excerpts, considering its religious, social, and economic dimensions within Saudi Arabia.
    3. Evaluate Saudi Arabia’s consistent stance on the Palestinian issue as presented in the excerpts, tracing its historical roots and highlighting the key principles guiding its policy.
    4. Critically assess the various challenges and opportunities facing the Kingdom in its efforts to balance economic development (as suggested by investment initiatives and market trends) with its commitment to social welfare and regional stability.
    5. Examine the role of cultural and heritage preservation initiatives, such as the Islamic Arts Biennale and the restoration of historical mosques, in promoting Saudi Arabia’s national identity and global image.

    Glossary of Key Terms

    • ولي العهد (Wali al-Ahd): The Crown Prince, the designated successor to the King.
    • مجلس الوزراء (Majlis al-Wuzara’): The Council of Ministers, the main executive body of the Saudi Arabian government.
    • ضيوف الرحمن (Duyuf al-Rahman): The guests of God, a term used to refer to pilgrims visiting Mecca and Medina.
    • القدس الشرقية (Al-Quds al-Sharqiya): East Jerusalem, considered by Palestinians as the capital of their future state.
    • قمة عربية غير عادية (Qimma Arabiya Ghair Aadiya): An extraordinary Arab Summit, convened to discuss urgent matters.
    • جسر جوي (Jisr Jawwi): An air bridge, a continuous series of flights to transport aid or personnel.
    • الهيئة السعودية لتسويق االستثمار (Al-Hay’a as-Saudiya li-Taswiq al-Istithmar): The Saudi Authority for Investment Marketing (translated based on context of promoting investment).
    • قمة فلسطين (Qimmat Filastin): The Palestine Summit (name given to an Arab League summit focused on the Palestinian issue).
    • الأونروا (Al-Unrwa): The United Nations Relief and Works Agency for Palestine Refugees in the Near East (UNRWA).
    • مبادرة السلام العربية (Mubadarat as-Salam al-Arabiya): The Arab Peace Initiative, a proposal for ending the Arab-Israeli conflict.
    • الحرمين الشريفين (Al-Haramayn ash-Sharifayn): The Two Holy Mosques, referring to the Grand Mosque in Mecca and the Prophet’s Mosque in Medina.
    • بينالي الفنون الإسلامية (Bienali al-Funun al-Islamiya): The Islamic Arts Biennale, a recurring exhibition of Islamic art.
    • صدقات (Sadaqat): Voluntary charitable giving in Islam.
    • الذوق العام (Al-Dhauq al-A’am): Public decency or etiquette.
    • رؤية المملكة 2030 (Ru’yat al-Mamlaka 2030): The Kingdom’s Vision 2030, a strategic framework to reduce Saudi Arabia’s dependence on oil, diversify its economy, and develop public service sectors.

    Briefing Document: Review of “20706.pdf” (Al Riyadh Newspaper, March 5, 2025)

    This briefing document summarizes the main themes, important ideas, and key facts presented in the provided excerpts from the Al Riyadh newspaper, issue 20706, dated March 5, 2025. The excerpts cover a range of domestic and international news, with a significant focus on Saudi Arabia’s policies, activities, and Ramadan preparations.

    I. Domestic Affairs and Policies:

    • Council of Ministers Meeting: The Council of Ministers, chaired by the Crown Prince Mohammed bin Salman, held a meeting in Riyadh.
    • The Crown Prince conveyed congratulations to Muslims on the arrival of Ramadan, emphasizing the Kingdom’s pride in serving the pilgrims of the Two Holy Mosques.
    • He affirmed the state’s continued support for the social services system aimed at providing suitable housing for eligible families, praising the cooperation between governmental, private, and non-profit sectors.
    • The Council approved the organization of the Saudi Investment Marketing Authority to attract individuals to various regions.
    • Support for “Palestine Summit” Decisions: The Council affirmed its full support for the resolutions of the “Palestine Summit” held in Cairo, which aims to reject the displacement of the Palestinian people and end the catastrophic consequences of the war, emphasizing the Palestinian people’s right to self-determination and the establishment of their independent state on the 1967 borders with East Jerusalem as its capital.
    • Saudi Arabia’s Stance on Palestine: The article highlights Saudi Arabia’s consistent and unwavering support for the Palestinian cause throughout history, starting from the London Conference in 1935. This support spans political, economic, social, and health dimensions, driven by a deep-rooted belief and commitment to the Arab and Islamic nation.
    • The Kingdom has provided financial aid, cared for the families of martyrs, and hosted a large number of Palestinians.
    • The article emphasizes the historical roles of King Abdulaziz, King Faisal (who sought to transform the Palestinian issue into a central Islamic cause), King Khalid, King Abdullah (who presented the first Arab initiative for Palestine), and King Fahd (as a political supporter).
    • Crown Prince Mohammed bin Salman reaffirmed that Jerusalem remains in the conscience of the leaders and peoples of Arab and Islamic nations, reiterating the Kingdom’s support until the Palestinian people achieve their legitimate rights and establish their independent state with East Jerusalem as its capital. He stated, “Let the near and the far know that Palestine and its people are in the conscience of Arabs and Muslims.”
    • Saudi Arabia contributed $150 million to the Islamic Endowments program in Jerusalem and $50 million to UNRWA.
    • The Kingdom stresses the necessity of a just and lasting solution to the Palestinian issue based on international legitimacy resolutions and the Arab Peace Initiative, ensuring the Palestinian people’s right to establish an independent state on the 1967 borders with East Jerusalem as its capital.
    • Saudi Arabia’s Ministry of Foreign Affairs stated in February 2025 that the Palestinian people’s right to their land is firm and cannot be taken away, emphasizing that lasting peace will only be achieved by returning to the logic of reason and accepting the principle of equal rights and human dignity.
    • Saudi Arabia ranks as a leading donor country to the Palestinian people, with total aid reaching $5,358,848,461 through 295 projects across various sectors.
    • Support for Lebanon: Despite regional political tensions, Saudi Arabia has maintained a strong presence and launched an airlift of humanitarian aid to support the Lebanese people facing ongoing challenges. Twenty-seven planes carrying relief supplies, including food, shelter, and medical materials, were dispatched.
    • The article suggests a new era of partnership with Lebanon, aiming to strengthen Arab relations, as reflected in the joint Saudi-Lebanese statement issued at the end of the Lebanese President’s visit, which emphasized the importance of enhancing joint Arab action and coordinating stances on key issues of the Arab and Islamic nation.
    • The Council of Ministers noted the joint statement between the Kingdom and Lebanon, emphasizing the importance of fully implementing the Taif Agreement regarding weapons and the state’s sovereignty over all its territories, and stressing the role of the Lebanese national army. It also reiterated the necessity of the Israeli occupation army’s withdrawal from all Lebanese territories.
    • Amir of Riyadh on King Salman Award for Quran Memorization: The Amir of Riyadh highlighted the significance of the King Salman bin Abdulaziz Award for Memorizing the Holy Quran in its content, methodology, and implementation.
    • Amir of Al-Qassim on Water Project: The Amir of Al-Qassim expressed gratitude for the approval of the Jubail-Buraidah water pipeline project, costing 8.5 billion riyals, noting its strategic importance in enhancing water security and supporting sustainable development in the region, aligning with Vision 2030. He praised the collaboration of various ministries and entities in executing the project according to the highest technical and engineering standards.
    • Development of Historical Mosques: The second phase of the Prince Mohammed bin Salman Project for the Development of Historical Mosques has been launched, aiming to preserve their architectural authenticity, restore them for worship and prayer, and highlight their religious and cultural significance. The first phase, launched in 2018, included the rehabilitation of 30 historical mosques in 10 regions.
    • Civil Defense Preparations for Ramadan: The Civil Defense in Makkah and Madinah has intensified its preventive supervision in the central area, accommodation facilities, and vital installations of the Two Holy Mosques to ensure the readiness of fire prevention and protection systems during Ramadan, aiming for the highest standards of readiness to serve pilgrims.
    • Comprehensive Operational System in the Two Holy Mosques: The General Authority for the Care of the Affairs of the Grand Mosque and the Prophet’s Mosque has completed its preparations to receive Ramadan 1446 AH, with a comprehensive operational system focused on managing assets, maintenance, enhancing the pilgrim experience, and coordinating with relevant entities to provide an integrated experience for Umrah performers and worshippers. This includes new services like mobile disinfection units, baggage storage development, increased electric golf carts, and improved I’tikaf experience.
    • Distribution of Iftar Meals in the Prophet’s Mosque: Approximately 227,000 Iftar meals are distributed daily in the Prophet’s Mosque during Ramadan.
    • Decline in Used Car Prices: Saudi Arabia has witnessed a 6% decrease in used car prices, marking the fifth consecutive monthly decline after previous significant increases. This is attributed to increased supply due to the availability of new models, regulatory measures by the Ministry of Commerce, and the opening of used car imports, enhancing competition. Car auctions have also played a significant role in lowering prices.
    • Increased Demand for Vegetables and Fruits in Ramadan: Traders expect a 65% increase in demand for fruits and vegetables during Ramadan, with stable prices due to a balance between supply and demand. They express confidence in the strength of the Saudi economy and the leadership’s vision, attracting suppliers. The Ministry of Environment, Water and Agriculture continues its plans to increase local production, aiming for self-sufficiency in line with Vision 2030.
    • Importance of Sustainable Social Solidarity in Ramadan: An article emphasizes that Ramadan is a season for social solidarity and helping the needy. However, it stresses the need to move beyond temporary seasonal aid towards creating sustainable impact through initiatives that empower individuals and improve quality of life through partnerships. Saudi companies are recognizing this shift.
    • Riyadh Season’s Ramadan Activities: Historic Jeddah is hosting “Ramadan 2025 Season” events, organized by the Historic Jeddah Program under the Ministry of Culture, aiming to revive cultural heritage, strengthen national identity, and offer visitors a unique experience throughout the holy month with diverse cultural and community activities.
    • Saudi Students’ Club in Liverpool Celebrates Founding Day: The Saudi Students’ Club in Liverpool held an event to commemorate the anniversary of the Kingdom’s founding.
    • Biannual Islamic Arts Exhibition: The Biannual Islamic Arts Exhibition in Jeddah is presenting unique artifacts and scenes under the theme “What is Between Them,” showcasing the history of Islamic arts, both ancient and contemporary. Notable exhibits include the “Dome Structure” previously used to preserve the Maqam Ibrahim.
    • Documenting Cultural Sites: The Ministry of Culture has documented historical sites associated with renowned Arab poets throughout the Kingdom, connecting the past with the present through informational signs.
    • “Riyadh Market as Seen by Belinken in 1947”: An article reflects on the depiction of the Riyadh market in 1947 by the British traveler Belinken, as part of tracing popular heritage in Western travelers’ accounts.
    • Ramadan Atmosphere in Mosques: A poem evokes the spiritual atmosphere of mosques in Riyadh during the nights and days of Ramadan.
    • National Awareness Campaign for Early Detection of Diseases: The Riyadh Health Cluster, in cooperation with the Health Holding Company, launched a national awareness campaign titled “Safety in Health” at the Saleh Al-Dossary Center to promote early detection and healthy lifestyles during Ramadan.
    • Saudi Arabian Motorsports Company Project Launch: The Saudi Arabian Motorsports Company, in cooperation with the General Directorate of Passports and the General Authority of Civil Aviation, launched the first phases of the Al-Mazar sports project, aiming to enhance the infrastructure for motorsports in the Kingdom.
    • Traditional Saudi Games: The Ministry of Interior, represented by the General Directorate of Border Guards, in cooperation with the Saudi Arabian Olympic & Paralympic Committee, concluded the first phase of a heritage initiative focusing on traditional Saudi games, considering them a renewed cultural heritage that strengthens national identity and belonging.
    • Ramadan Legacy: An article reflects on the unique spiritual and social atmosphere of Ramadan in Saudi society, emphasizing traditions of unity, generosity, and strengthening community bonds.
    • Community Iftar Gatherings: The article highlights the tradition of community Iftar gatherings in neighborhoods, fostering unity and recalling fond memories during Ramadan, with appreciation for the efforts of local authorities and community centers in supporting these initiatives.

    II. International Affairs:

    • Sudan Crisis: Saudi Arabia reiterates its unwavering support for the unity, safety, stability, and territorial integrity of Sudan, rejecting any illegitimate steps taken outside the framework of official Sudanese institutions that could undermine its unity. The Kingdom calls on Sudanese parties to prioritize Sudan’s interests and avoid division and chaos, reaffirming its commitment to ending the war and achieving peace in accordance with the Jeddah Declaration signed on May 11, 2023.
    • The Ministry of Foreign Affairs statement underscores the importance of continued efforts to halt the conflict and work towards peace, recalling the Jeddah Declaration which outlined commitments by the Sudanese Armed Forces and the Rapid Support Forces to protect civilians and facilitate humanitarian action.
    • Gaza Conflict: The Arab League summit in Cairo adopted an Arab plan for early recovery and reconstruction of Gaza to counter attempts to liquidate the Palestinian issue. The plan urges all types of financial, material, and political support for its implementation and calls on the international community and international and regional financing institutions to provide necessary support.
    • The statement stressed the strategic option of achieving a just, comprehensive, and lasting peace that fulfills all the rights of the Palestinian people, especially their right to freedom and an independent state with sovereignty over their national soil based on the two-state solution, ensuring security for all peoples and states of the region, including Israel.
    • The Arab countries reaffirmed their commitment to resolving all conflicts and disputes in the region peacefully and establishing normal relations and cooperation among all its countries, while firmly rejecting all forms of occupation and aggression.
    • The statement emphasized intensifying cooperation with international and regional powers, including the United States, to achieve a just and comprehensive peace in the Middle East, working to end all conflicts and expressing readiness to engage immediately with the US administration and all international partners to resume peace negotiations aimed at a just settlement of the Palestinian issue, ending the Israeli occupation and establishing the independent and sovereign Palestinian state on the June 4, 1967 borders with East Jerusalem as its capital, living in peace and security alongside Israel, and calling for the convening of an international peace conference.
    • The statement welcomed the Palestinian decision to work on enabling the National Authority to return to the Palestinian territories occupied since 1967, as a embodiment of unity for a transitional period in Gaza. It also valued the proposal from Jordan and Egypt to qualify and train Palestinian cadres to ensure their ability to fully perform their security duties in Gaza, stressing that the security file is a Palestinian responsibility that must be managed by the legitimate Palestinian institutions alone, according to the principle of one law, one authority, and one legitimate weapon, ensuring its continuous stability.
    • The statement highlighted the need to address Israel’s concerns regarding long-term security in Gaza.
    • Conversely, it noted Israeli Prime Minister Netanyahu’s use of withholding aid as leverage to evade the second phase of ceasefire negotiations.
    • The continuation of border closures and prevention of aid entry exacerbates the humanitarian crisis in Gaza, where over two million Palestinians face dire living conditions due to the ongoing Israeli war.
    • Security Campaign in Latakia, Syria: A security campaign was launched in Latakia following the killing of two security personnel in an “armed ambush,” coinciding with alleged Israeli airstrikes on weapons depots in the Qardaha area.
    • UNICEF Report on Sexual Violence in Sudan: UNICEF announced that Sudanese fighters have raped Sudanese civilians, including children as young as one year old, during the ongoing civil war, in what could amount to “war crimes.” The report details harrowing testimonies of survivors and highlights the limited data available, indicating the actual scale of sexual violence is likely much larger. UNICEF calls for an immediate end to this suffering.
    • Alleged “Rapid Support Forces” Bombing in Al-Fashir, Sudan: The “Rapid Support Forces” are accused of shelling a market in Al-Fashir, killing six civilians and injuring an unknown number. The Rapid Support Forces control most of Darfur region and are besieging Al-Fashir, the last major city under the control of the army and allied factions. Famine has spread in areas surrounding Al-Fashir, raising fears it could extend to the city itself.
    • Liverpool vs. Paris Saint-Germain Champions League Match: An article previews the upcoming Champions League Round of 16 first-leg match between Liverpool and Paris Saint-Germain, noting Liverpool’s strong form in the English Premier League and PSG’s dominance in Ligue 1, while highlighting PSG’s less convincing performance in the Champions League group stage.
    • Bayern Munich vs. Bayer Leverkusen Match: An article discusses the upcoming Bayern Munich vs. Bayer Leverkusen match in the Bundesliga, noting Leverkusen’s impressive undefeated run and Bayern’s strong record against Leverkusen at home, predicting a challenging encounter for both teams.
    • Benfica vs. Barcelona Match: Barcelona will visit Benfica, aiming to restore their status as one of the continent’s giants.
    • Al-Hilal Loses to Pakhtakor in AFC Champions League: Al-Hilal lost 2-1 to Pakhtakor of Uzbekistan in the first leg of the AFC Champions League Round of 16, despite taking an early lead.
    • Al-Ahli Closer to AFC Champions League Quarter-Finals: Al-Ahli defeated Qatari side Al-Rayyan 3-1 in the first leg of their AFC Champions League Round of 16 tie, putting them in a strong position to advance.
    • Saudi National Football Team Preparations for World Cup Qualifiers: The Saudi national football team is preparing for a crucial match against China on March 20th in the qualifiers for the 2026 World Cup. The article expresses hope for the team’s success in their quest to qualify for the World Cup for the seventh time in their history.
    • Asian Qualifiers for Under-17s Championship Draw: The draw for the Asian Qualifiers for the Under-17s Championship in January placed Saudi Arabia in Group A along with China, Thailand, and Uzbekistan.

    III. Economic and Financial News:

    • Gold Prices Rise: Gold prices increased due to demand for safe-haven assets amid trade tensions sparked by US President Donald Trump imposing new tariffs on major trading partners. Spot gold rose 0.8% to $2917.61 per ounce, marking the second consecutive session of gains.
    • Gulf Stock Markets Decline: Most Gulf stock markets experienced declines.
    • Saudi Aramco Financial Results: Saudi Aramco announced a net income of 121.3 billion Saudi Riyals (SAR) ($32.3 billion USD) in 2024. The decrease in net income compared to the previous year was attributed to lower revenues due to decreased crude oil prices and refined and chemical product prices, partially offset by higher sales volumes of refined and chemical products.
    • Saudi Aramco’s President and CEO, Amin H. Nasser, stated that the strong net income and dividends reflect the company’s exceptional resilience, ability to capitalize on its unique scale and low-cost production, and reliable delivery to customers and shareholders. He noted that global oil demand reached new highs in 2024 and expects further growth in 2025.
    • The company is progressing with projects aimed at maintaining its maximum sustainable crude oil production capacity and ensuring reliable energy supplies.
    • Saudi Aramco has made progress in its growth strategy across upstream, refining, chemicals, and marketing sectors, with potential additional operating cash flows expected from these expansions by 2030.
    • The company’s spare capacity provides flexibility to meet potential oil demand growth.
    • Chairman of Saudi Aramco’s Board of Directors, Yasser bin Othman Al-Rumayyan, highlighted the strong dividends distributed to shareholders since the IPO and the significant investor interest in Saudi Aramco’s continued growth story through a secondary public offering and issuance of international bonds and sukuk in 2024.
    • Darren Woods of ExxonMobil and Philippe Novac of TotalEnergies on Oil Prices: They commented on the current downward trend in oil prices, attributing it to OPEC+ production increases and US tariffs, along with geopolitical developments related to the Russia-Ukraine conflict.
    • President Trump’s Halt to US Military Aid to Ukraine: This decision, following a disagreement with President Zelensky, and OPEC+’s decision to proceed with planned oil production increases, have influenced oil market dynamics.
    • China’s Response to US Tariffs: Following the implementation of US tariffs, China quickly announced retaliatory import duty increases on a range of US agricultural and food products.
    • Reliance Industries to Resume Activities in India: The Indian company will resume its activities in India from March 5, 2025, after resolving a gas drilling dispute with the Indian government.
    • Trump’s Inspiration from the Saudi Sovereign Wealth Fund: An analysis discusses US President Donald Trump’s stated intention to create a large American sovereign wealth fund, drawing inspiration from the successful Saudi Public Investment Fund (PIF), which is currently ranked among the largest globally. The analysis explores the concept of sovereign wealth funds in the US, noting existing state-level funds, and discusses potential sources of funding and governance structures for a federal fund, emphasizing the need for transparency and independence from political interference.

    IV. Social and Cultural Items:

    • The Value of Water: An article highlights the essential role of water for life, its unique properties, and its abundance in the universe in frozen form, with liquid water being unique to Earth. It emphasizes the human body’s high water content and the intricate system of water on the planet, referencing Quranic verses about the creation of water.
    • Obituary for Moroccan Intellectual Mohammed bin Issa: An obituary commemorates the passing of Mohammed bin Issa, a prominent figure in Moroccan thought, culture, and politics, and the founder of the Asilah Cultural Festival, recognizing his significant contributions and lasting impact.

    V. Health News:

    • Surgical Removal of Pancreatic Tumor: Dr. Mostafa Habib Soliman performed a successful “Whipple” procedure to remove a cancerous hormonal tumor from the pancreas of a patient suffering from severe abdominal pain.
    • The Benefits of Fasting During Ramadan: An article discusses the various health benefits associated with fasting during Ramadan, referencing scientific studies on intermittent fasting and its impact on autophagy, inflammation, insulin sensitivity, weight loss (specifically abdominal fat), and mental well-being through increased serotonin and reduced stress hormones. It also notes potential benefits in reshaping the relationship with food by reducing cravings for sugary items. However, it cautions that prolonged fasting without proper nutrition can lead to adverse effects like dehydration or hypoglycemia, especially for individuals with chronic conditions who require medical supervision.
    • Impact of Ramadan on Sleep: A study from the University of the Emirates found that the quality of sleep improved for participants during Ramadan, likely due to reduced caffeine intake and regulated melatonin secretion.
    • Seizure of Pharmaceutical Products and Fine for Factory: The Saudi Food and Drug Authority (SFDA) reported seizing over 100,000 packages of 29 different unregistered pharmaceutical and nerve medications from a factory in violation of regulations. The factory was fined 1.4 million riyals and referred to the Public Prosecution. The SFDA emphasized the importance of adhering to regulations and called on the public to report violations.

    This briefing document provides a comprehensive overview of the key information presented in the selected excerpts from the Al Riyadh newspaper. It highlights Saudi Arabia’s active role in regional politics, its ongoing domestic development initiatives, preparations for the holy month of Ramadan, and various economic, social, and health-related news items.

    Saudi Arabia: Key Policy Updates and Initiatives

    Frequently Asked Questions

    1. What was the primary focus of the Saudi Council of Ministers’ meeting? The primary focus of the Saudi Council of Ministers’ meeting, chaired by Crown Prince Mohammed bin Salman, was on two key areas: expressing gratitude for the opportunity to serve pilgrims to the Two Holy Mosques during Ramadan and reiterating the Kingdom’s commitment to supporting social services for its citizens. Additionally, the council addressed regional and international matters, including the Palestinian issue, the situation in Lebanon, and international economic developments.
    2. What is Saudi Arabia’s stance on the Palestinian issue, as highlighted in the sources? Saudi Arabia maintains a firm and long-standing supportive stance towards the Palestinian issue. The Kingdom calls for the establishment of an independent Palestinian state based on the 1967 borders, with East Jerusalem as its capital. It strongly condemns the Israeli government’s actions, including the obstruction of humanitarian aid to Gaza, and urges the international community to hold Israel accountable and ensure sustained aid access. Saudi Arabia also emphasizes its support for the Palestinian National Authority in its efforts to govern Gaza and provide essential services. This position is rooted in the Kingdom’s historical and religious commitment to the Palestinian people.
    3. How is Saudi Arabia addressing the situation in Lebanon, according to the provided text? Saudi Arabia is actively engaging with Lebanon to foster a new era of partnership. Despite past political tensions, the Kingdom has sent significant humanitarian aid to Lebanon, including food, shelter, and medical supplies. The joint Saudi-Lebanese statement released after the Lebanese President’s visit underscores the importance of fully implementing the Taif Agreement, ensuring the Lebanese state’s sovereignty and control over its territory (including border control and arms control), and the withdrawal of the Israeli occupation army from all Lebanese territories.
    4. What initiatives are being undertaken to enhance the experience of pilgrims visiting the Two Holy Mosques during Ramadan? Significant efforts are underway to provide a comprehensive and comfortable experience for pilgrims during Ramadan. These include an integrated operational system for managing the Grand Mosque and the Prophet’s Mosque, focusing on maintenance, efficient operations, and enriching the visitor experience. Specific initiatives include the launch of “Tahalul Service” using mobile units for hair shaving (an Umrah ritual), development of a luggage storage service with electronic tracking, increasing the number of electric golf carts for transportation within the mosques, developing manual carts with a unified design, enhancing Itikaf (seclusion) services, improving the electronic booking system for Iftar meals, providing categorized guidance signs, operating centers for children’s hospitality, and offering religious and cultural exhibitions like “First House” which showcases the history of the Kaaba’s construction.
    5. What developments were reported regarding the Saudi economy and specific sectors? Several economic developments were highlighted. The Saudi Council of Ministers approved the organization of the Saudi Investment Marketing Authority. The used car market saw a 6% price decrease due to increased supply and the allowance of used car imports. Conversely, gold prices continued to rise, driven by demand for safe-haven assets amidst international trade tensions. The Saudi stock market generally saw declines, mirroring global trends influenced by factors like potential interest rate cuts and geopolitical concerns.
    6. How is Saudi Arabia preserving and promoting its cultural and historical heritage, as mentioned in the text? Saudi Arabia is actively working to preserve and promote its cultural and historical heritage through various initiatives. The second phase of the Prince Mohammed bin Salman Project for the Development of Historical Mosques has been launched, focusing on restoring and architecturally preserving these significant sites while allowing for non-impactful additions. The Ministry of Culture is also documenting historical locations associated with renowned Arab poets, like the site in Najran where Yaguth bin Abdullah Al-Harthy lived, transforming it into a public park. Additionally, the Islamic Arts Biennale is showcasing rare artifacts and unique displays, such as the former domed structure used to protect the Maqam Ibrahim in Mecca, highlighting the rich history of Islamic art and culture.
    7. What role is Saudi Arabia playing in addressing the ongoing conflict in Sudan? Saudi Arabia is deeply concerned about the situation in Sudan and is actively engaged in efforts to mediate and resolve the conflict. The Kingdom has repeatedly emphasized the importance of Sudan’s unity, safety, stability, and territorial integrity, rejecting any external interference in its internal affairs or the formation of parallel governments. Saudi Arabia hosted Sudanese parties in Jeddah, which led to the signing of the “Jeddah Declaration” in May 2023, outlining commitments to protect civilians and facilitate humanitarian aid. The Kingdom continues to urge all Sudanese factions to prioritize Sudan’s interests over any partisan agendas and to work towards a peaceful resolution, in line with the Jeddah Declaration.
    8. Beyond immediate aid, how is social solidarity and community support being fostered in Saudi Arabia, particularly during Ramadan? Saudi Arabia is moving beyond solely providing immediate, seasonal aid to fostering sustainable social solidarity and community support. During Ramadan, there is a notable increase in charitable initiatives, with institutions and individuals competing to help those in need. Companies are adopting long-term approaches, focusing on empowering vulnerable groups through initiatives that provide job opportunities and support small businesses, contributing to improved quality of life through partnerships. Community iftars (breaking fast meals) are also a significant tradition, strengthening bonds and fostering a sense of unity among neighbors and friends across different neighborhoods. These gatherings, often organized by volunteers and supported by local authorities, highlight the strong social fabric of Saudi society.

    Saudi Arabia and Lebanon: Strengthening Bilateral Relations

    Based on the sources, Saudi Arabia and Lebanon share historical ties and are working towards strengthening their relationship in various fields.

    Historical Context and Support:

    • Historically, the Kingdom of Saudi Arabia has supported Lebanon’s security, stability, politically, economically, and socially.
    • Saudi Arabia played a role in stopping the Lebanese civil war through the “Taif Agreement”.

    Recent Developments and Cooperation:

    • The President of the Lebanese Republic, Joseph Aoun, recently paid an official visit to Saudi Arabia, marking a potential new phase in Saudi-Lebanese relations.
    • The visit aimed to boost bilateral relations and cooperation in various fields, including the economy, in line with the aspirations of the Lebanese people.
    • During the visit, discussions covered various aspects of the relationship and ways to develop it in all fields, in addition to discussing regional and international developments.
    • Both sides emphasized the importance of enhancing joint Arab action and coordinating stances towards important regional and international issues.

    Key Areas of Emphasis in Joint Statements:

    • Taif Agreement: Both Saudi Arabia and Lebanon stressed the importance of the full implementation of the Taif Agreement as the foundation for political balances in Lebanon. Saudi Arabia views the full implementation of this agreement as the sole guarantee to prevent Lebanon from slipping towards a constitutional vacuum or political chaos.
    • State Sovereignty and Security: The importance of extending the state’s authority over all Lebanese territories and confining arms to the Lebanese state was highlighted.
    • Withdrawal of Israeli Forces: Both nations reiterated the necessity of the withdrawal of the Israeli occupation army from all Lebanese territories.
    • Economic Recovery: Agreement was reached on the necessity of the Lebanese economy’s recovery and overcoming its current crisis by initiating internationally required reforms based on the principles of transparency and the application of binding laws. Saudi Arabia has historically sought Lebanon’s stability.
    • Arab Identity: The joint statement emphasized that Lebanon’s Arab relations are essential for its security and stability.
    • Resumption of Exports: Both sides agreed to study obstacles hindering the resumption of Lebanese exports to the Kingdom of Saudi Arabia.

    Challenges and Past Issues:

    • Despite past political repercussions that distanced the Lebanese, Saudi Arabia has continued to provide humanitarian aid to the Lebanese people, including an airlift carrying 27 shipments of relief aid containing food, shelter, and medical supplies.
    • There was a continuous debate within Lebanon regarding the Taif Agreement, leading to the Saudi-Lebanese reiteration of its importance.

    Future Outlook:

    • The recent meeting is seen as a prelude to strengthening relations and looking towards the future under the title of “Partnership for a New Era”.
    • Saudi Arabia blesses every sincere effort that seeks the good of the Arab nation and its unity.
    • Lebanon, looking to turn a page on the past, sees the enhancement of relations with Saudi Arabia as a priority.

    In conclusion, Saudi-Lebanese relations are characterized by historical support, a recent push for renewed cooperation across various sectors, and a shared vision on key regional and domestic issues for Lebanon, particularly emphasizing the importance of the Taif Agreement and Lebanese sovereignty.

    Saudi Arabia’s Support for Lebanon: Dimensions and Commitments

    Drawing on the sources and our conversation history, the support for Lebanon is a significant aspect of Saudi Arabia’s engagement with the country. This support is multifaceted, encompassing historical, political, security, and economic dimensions.

    Historical Support:

    • The Kingdom of Saudi Arabia has historically supported Lebanon’s security, stability, and its political, economic, and social well-being.
    • Saudi Arabia played a crucial role in brokering the “Taif Agreement,” which aimed to end the Lebanese civil war.

    Recent Support and Cooperation:

    • The recent official visit of the Lebanese Republic’s President, Joseph Aoun, to Saudi Arabia underscores a renewed commitment to strengthening bilateral relations in various fields, including the economy. This visit is seen as a potential “new phase for Saudi-Lebanese relations”.
    • Discussions during the visit covered various aspects of the relationship, aiming to develop it across all sectors, alongside discussions on regional and international developments.
    • Both Saudi Arabia and Lebanon emphasized the importance of boosting joint Arab action and coordinating their positions on significant regional and international issues.

    Key Areas of Emphasis in Supporting Lebanon:

    • The Taif Agreement: Both nations have consistently highlighted the importance of the full implementation of the Taif Agreement. Saudi Arabia views this agreement as the fundamental basis for political equilibrium in Lebanon and the primary safeguard against constitutional voids or political instability.
    • Lebanese Sovereignty and Security: A central tenet of the support is the emphasis on extending the Lebanese state’s sovereignty over all its territories. This includes the crucial aspect of confining arms to the Lebanese state. The joint statement explicitly mentions the importance of the Lebanese national army’s role and supporting it in this endeavor.
    • Withdrawal of Israeli Forces: Both Saudi Arabia and Lebanon have reiterated the necessity of the complete withdrawal of the Israeli occupation army from all Lebanese territories. This remains a consistent point of agreement and support for Lebanon’s territorial integrity.
    • Economic Recovery: Recognizing the current economic challenges in Lebanon, both sides have agreed on the necessity of the Lebanese economy’s recovery and overcoming its crisis. This involves initiating internationally required reforms grounded in transparency and the application of binding laws. Saudi Arabia has historically been invested in Lebanon’s stability, which inherently includes its economic well-being. They also agreed to study the obstacles hindering the resumption of Lebanese exports to Saudi Arabia.
    • Arab Identity: The joint statements have emphasized that Lebanon’s Arab relations are fundamental to its security and stability. This highlights a shared understanding of Lebanon’s place within the broader Arab context.
    • Blessing Sincere Efforts: Saudi Arabia has expressed its support by “blessing every sincere effort that seeks the good of the Arab nation and its unity,” which implicitly includes efforts towards Lebanon’s stability and progress.
    • Lebanon’s Perspective: Lebanon, as indicated, prioritizes the enhancement of its relations with Saudi Arabia, viewing it as a crucial step in overcoming past issues and looking towards a more stable future. The Lebanese President’s choice of Riyadh as his first foreign visit further underscores this priority.

    In summary, the support for Lebanon from Saudi Arabia is rooted in historical ties and continues through active engagement and a shared vision for Lebanon’s sovereignty, security, and economic recovery. Key to this support is the emphasis on the Taif Agreement as a foundational element for Lebanon’s stability and the need for a strong, sovereign Lebanese state.

    Global Trade Activities and Interconnected Economies

    Based on the sources provided, there is some information that touches upon aspects of global trade, although none of the sources directly discuss a “global trade war” as a central topic. However, we can infer related concepts and activities:

    • Source mentions that the price of copper fell slightly on Tuesday due to the weight of customs tariffs policies pursued by Trump on the metal. Investors in the red metal were also cautiously awaiting meetings of China’s parliament to gain insight into potential economic stimulus measures aimed at boosting domestic demand. This indicates how national trade policies and economic conditions in major economies can influence global commodity markets.
    • Sources and discuss the import of used cars into Saudi Arabia. The increased availability of used cars from abroad has intensified competition, contributing to lower prices for consumers in Saudi Arabia. Car auctions in the Kingdom also provide an environment for competitive pricing, including for imported vehicles. These points illustrate the flow of goods across borders and the impact of international trade on local markets and consumer prices.
    • Source notes that during the month of Ramadan, Saudi Arabia receives imports of certain fruits and vegetables by air, sea, and land to ensure stable prices and availability. This highlights the reliance on international trade to meet domestic consumption needs, especially during peak demand periods.
    • Source mentions that Saudi Aramco issued international bonds in July, with subscriptions exceeding the initial target size due to strong demand from a diverse base of both existing and new institutional investors. In October, Aramco also completed the issuance of dollar-denominated international Sukuk, which also saw subscriptions exceeding several times the target size. This demonstrates Saudi Arabia’s engagement with global financial markets and the flow of capital across borders.
    • Source discusses a thought-provoking question about where Saudi Arabia’s sovereign wealth fund should invest. It mentions a suggestion that the fund might find it best to invest the majority of its capital in private markets and basic infrastructure in the United States, driven by a strategic mandate and the philosophy of directing funds towards federal priorities. This reflects considerations around international investment strategies and their alignment with national interests and global economic landscapes.

    While these instances do not provide a comprehensive discussion of a “global trade war,” they offer glimpses into international trade activities, the impact of national economic policies on global markets (tariffs), and the interconnectedness of economies through the flow of goods and investments. The mention of tariffs in the context of copper prices is the most direct link to the concept of trade tensions, as tariffs are a common tool used in trade disputes.

    Saudi Arabia and the Palestinian Cause

    Based on the sources, the Palestinian cause is a significant and consistently addressed issue. Saudi Arabia maintains a firm and unwavering stance in defense of the rights of the Palestinian people.

    Key aspects of the Saudi Arabian position on the Palestinian cause, as highlighted in the sources, include:

    • Rejection of Displacement: Saudi Arabia strongly rejects the displacement of the Palestinian people from their lands. This was emphasized during the extraordinary Arab Summit “Summit of Palestine” held in Egypt. The Kingdom reiterates this stance, stressing its categorical refusal to infringe upon the legitimate rights of the Palestinian people through any means, including settlement policies or attempts to displace them.
    • Support for Legitimate Rights: Saudi Arabia affirms the right of the Palestinian people to their legitimate rights. This includes their right to self-determination and to establish their independent state on the borders of 1967 with East Jerusalem as its capital.
    • Condemnation of Israeli Occupation: The sources indicate a strong condemnation of the Israeli occupation and its actions. The need for the withdrawal of the Israeli occupation army from all Lebanese territories is repeatedly stressed, which reflects a broader concern about Israeli occupation in the region. Saudi Arabia denounces the Israeli occupation authority’s crimes against the Palestinian people, highlighting the suffering caused by the occupation and its disregard for international law.
    • Support for International Resolutions: Saudi Arabia emphasizes the importance of the full implementation of relevant international resolutions concerning the Palestinian issue.
    • Humanitarian Aid: The Kingdom actively contributes to alleviating the humanitarian situation in the Gaza Strip and its surroundings. The developmental assistance provided by Saudi Arabia to the State of Palestine and the Palestinian people through the Saudi Fund for Development has reached approximately $4.812 billion, covering sectors such as education, health, housing, and refugee housing.
    • Advocacy in International Forums: Saudi Arabia, under its leadership, consistently underscores its firm positions on the Palestinian issue in various international forums. The Kingdom’s commitment to defending the Palestinian cause is evident in its statements and actions, including the address to the Shura Council, where the Palestinian cause was highlighted as a top priority.
    • Efforts for a Peaceful Resolution: Saudi Arabia supports efforts to reach a comprehensive and just solution to the Palestinian cause. The statement highlights the positive role of Qatar and Egypt, in cooperation with the US administration, in reaching a ceasefire in Gaza and the release of hostages. It also mentions the importance of building on these efforts to develop an executive plan for a lasting solution. The Kingdom, as the chair of the Arab Islamic Committee on Gaza and in partnership with the European Union, supports the holding of an international conference, co-chaired by Saudi Arabia and France, to find and implement a solution to the Palestinian issue.
    • Rejection of Harm to Holy Sites: The statement also affirms the support for the Hashemite custodianship of the holy sites, which is relevant to the status of Jerusalem.

    In conclusion, the Palestinian cause is a central pillar of Saudi Arabia’s foreign policy, characterized by a firm commitment to Palestinian rights, rejection of Israeli occupation and displacement, provision of humanitarian aid, and active engagement in regional and international efforts to achieve a just and lasting solution based on relevant international resolutions and the establishment of an independent Palestinian state with East Jerusalem as its capital.

    Saudi Arabia Economic Activities and Initiatives

    Based on the sources, Saudi Arabia’s economy is multifaceted, with significant activities in energy, trade, investment, and social development.

    Energy Sector:

    • Saudi Aramco achieved profits and cash flows in its 2024 results despite lower oil prices. This indicates the continued importance of the oil sector to the Saudi economy.
    • Aramco issued international bonds in July, with strong investor demand. This reflects the company’s access to global financial markets and the confidence of international investors in the Saudi energy giant.
    • In October, Aramco also completed the issuance of dollar-denominated international Sukuk, which was also oversubscribed. This further demonstrates Aramco’s role in international finance.
    • Saudi Aramco has a keen interest in increasing oil production capacity from its fields to maintain its role in the global oil market in the coming years.

    Trade and Imports:

    • Saudi Arabia experiences imports of used cars, which have increased competition and led to lower prices for consumers. This highlights the impact of international trade on the domestic automotive market.
    • During the month of Ramadan, the Kingdom imports fruits and vegetables by air, sea, and land to ensure stable prices and meet increased demand. This reliance on international trade is crucial for food security, especially during peak consumption periods.
    • Saudi Arabia agreed with Lebanon to study the obstacles hindering the resumption of Lebanese exports to the Kingdom. This suggests an interest in fostering bilateral trade relations.

    Investment and Finance:

    • The Saudi Authority for Investment Marketing is being organized, indicating a government focus on attracting and promoting investment in the Kingdom.
    • There is discussion about where Saudi Arabia’s sovereign wealth fund should invest, with a suggestion to focus on private markets and basic infrastructure in the United States. This highlights the strategic considerations involved in managing the Kingdom’s substantial financial reserves and their potential global impact. Our previous conversation mentioned that Saudi Arabia is a country with sovereign wealth funds due to financial surpluses.
    • Saudi Arabia’s sovereign wealth fund is described by Donald Trump as a “big sovereign fund”.

    Government Economic Initiatives and Approvals:

    • The establishment of the Saudi Building Code Academy has been approved in principle. This indicates a focus on developing expertise and standards in the construction sector.
    • The Council of Ministers affirmed the state’s continued support for the social services system and national initiatives aimed at providing suitable housing for eligible families. This reflects a government commitment to social welfare and improving living standards.
    • The Council also reviewed the progress of major development and service projects underway to enhance the Kingdom’s comprehensive renaissance, including the Riyadh Metro project. These projects signify significant government investment in infrastructure development.

    Social Welfare and Support Programs:

    • The state continues to support social services and initiatives to provide housing for those who deserve it.
    • The “Joud Eskan” (Good Housing) campaign is mentioned, emphasizing collaboration between government, private, non-profit sectors, and individuals to achieve its goals.
    • There is mention of social security being easier and more accessible through electronic means, supported by programs like “Citizen’s Account,” “Hafiz,” “Maharah,” “Reef,” and “Manaa”. These initiatives aim to support limited-income individuals, entrepreneurs, and investors.

    In summary, Saudi Arabia’s economy is heavily influenced by its strong energy sector, particularly through the activities of Saudi Aramco in production and international finance. The Kingdom actively engages in international trade to meet domestic needs and is also focused on attracting investment through initiatives like the Saudi Authority for Investment Marketing. The government demonstrates a commitment to social welfare and infrastructure development through various programs and projects. The strategic management of the sovereign wealth fund also plays a crucial role in the Kingdom’s long-term economic outlook.

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

  • Express.js: Building RESTful APIs and Dynamic Templates

    Express.js: Building RESTful APIs and Dynamic Templates

    This comprehensive guide covers Node.js and Express.js, starting with basic concepts like Node modules and event emitters, and progressing to building custom emitters. The material then transitions to Express.js, explaining routing, middleware, template engines, and RESTful API development, including how to create dynamic routes. It further explores REST API structure with MongoDB, including setting up a database, creating schemas, and performing CRUD operations. The guide also addresses user authentication, including registration, login, cookie management, and role-based authorization. Advanced topics like aggregation pipelines and document references in MongoDB are then discussed. Finally, the guide introduces TypeScript with Node.js, focusing on setting up a TypeScript project, using interfaces, and integrating it with Express.js and Mongoose.

    Comprehensive Node.js Study Guide

    Quiz

    Answer each question in 2-3 sentences.

    1. What is the purpose of the Node.js module system?
    2. Explain the difference between module.exports and require in Node.js.
    3. What is the module wrapper in Node.js, and what parameters does it include?
    4. What is npm, and what are some key npm commands?
    5. What does the path module provide in Node.js, and give an example of how it’s used?
    6. How does the file system (fs) module work in Node.js?
    7. What are streams in Node.js, and why are they useful?
    8. Explain the difference between synchronous and asynchronous code execution.
    9. Describe promises in JavaScript and how they are used to handle asynchronous operations.
    10. What are async and await keywords used for and how do they relate to promises?

    Quiz Answer Key

    1. The Node.js module system allows developers to organize code into reusable pieces, promoting modularity and manageability. It allows for code to be split into multiple files and then each file can be treated as a separate module. This helps in creating large applications.
    2. module.exports is used to expose functionality (variables, functions, objects) from a module, making it available for use in other modules. require is used to import the functionality that has been exported from another module.
    3. The module wrapper is a function that wraps every Node.js module before it is executed, providing scope and access to module-specific variables. It includes parameters like exports, require, module, __filename (file name), and __dirname (directory name).
    4. npm (Node Package Manager) is the default package manager for Node.js, used to install, manage, and publish packages. Key commands include npm init (initialize a new project), npm install (install packages), npm uninstall (uninstall packages), and npm start (run scripts defined in package.json).
    5. The path module provides utilities for working with file and directory paths. For example, path.join() can be used to combine multiple path segments into a single path.
    6. The file system (fs) module allows interaction with the file system, enabling operations such as reading files, writing files, creating directories, and checking file existence. Functions like fs.readFile() read from files and functions like fs.writeFile() write to files.
    7. Streams in Node.js are a way to handle reading and writing data sequentially, piece by piece, instead of all at once. They are useful for processing large files or data flows efficiently, preventing memory overload.
    8. Synchronous code executes line by line, with each operation completing before the next one starts, blocking the execution thread. Asynchronous code allows multiple operations to run concurrently without blocking, typically using callbacks, promises, or async/await.
    9. Promises are JavaScript objects that represent the eventual completion (or failure) of an asynchronous operation. They provide a cleaner way to handle asynchronous code, avoiding callback hell and enabling better error handling through .then() and .catch() methods.
    10. async is used to define asynchronous functions that implicitly return a promise, while await is used inside async functions to pause execution until a promise is resolved. This syntax makes asynchronous code look and behave more like synchronous code, improving readability.

    Essay Questions

    1. Discuss the advantages and disadvantages of using the Node.js module system for organizing code in large applications. How does this system compare to other module systems in languages like Python or Java?
    2. Explain the concept of asynchronous programming in Node.js, detailing how callbacks, promises, and async/await are used to manage non-blocking operations. Provide examples of scenarios where asynchronous programming is essential for performance.
    3. Compare and contrast the use of streams and buffers in Node.js. Describe situations where streams are preferable to buffers and explain how streams can improve the efficiency of file processing.
    4. Describe the role of npm in Node.js development. Discuss the importance of package.json for managing dependencies and explain how semantic versioning is used to handle package updates and compatibility.
    5. Explain how to use the module wrapper and how it allows for parameters such as require, module, filename, and dirname to be used. Give examples of each one.

    Glossary of Key Terms

    • Module System: A feature of Node.js that allows code to be organized into reusable units called modules.
    • module.exports: A Node.js object that is used to expose functions, objects, or values from a module so they can be used by other parts of the application.
    • require: A Node.js function used to import modules and their exported values into the current file.
    • Module Wrapper: A function that wraps every Node.js module, providing a private scope and access to module-specific variables like exports, require, module, __filename, and __dirname.
    • npm (Node Package Manager): The default package manager for Node.js, used to install, manage, and publish packages.
    • npm init: An npm command that initializes a new Node.js project and creates a package.json file.
    • npm install: An npm command that installs packages and their dependencies into the current project.
    • npm uninstall: An npm command that removes packages from the current project.
    • npm start: An npm command that runs scripts defined in the package.json file, typically used to start the application.
    • package.json: A JSON file that contains metadata about a Node.js project, including dependencies, scripts, and project information.
    • Path Module: A Node.js module that provides utilities for working with file and directory paths.
    • File System (fs) Module: A Node.js module that provides methods for interacting with the file system, such as reading and writing files, creating directories, and checking file existence.
    • Streams: A way to handle reading and writing data sequentially, piece by piece, instead of all at once.
    • Synchronous Code: Code that executes line by line, with each operation completing before the next one starts.
    • Asynchronous Code: Code that allows multiple operations to run concurrently without blocking, typically using callbacks, promises, or async/await.
    • Promises: JavaScript objects that represent the eventual completion (or failure) of an asynchronous operation.
    • async: A keyword used to define asynchronous functions that implicitly return a promise.
    • await: A keyword used inside async functions to pause execution until a promise is resolved.

    Node.js Development: Concepts and Practices

    Okay, here’s a detailed briefing document summarizing the key themes and ideas from the provided text excerpts.

    Briefing Document: Node.js Development Concepts

    Overview:

    This document summarizes key concepts related to Node.js development, as presented in the provided text. The excerpts cover basic syntax, module systems, package management with NPM, core modules like path and fs (file system), asynchronous programming with Promises and Async/Await, basic HTTP server creation, database interaction using Mongoose with MongoDB, project structuring, authentication with JWT, file uploads with Multer, role-based access control, testing with Jest, deployment to Render and Vercel, and GraphQL basics including schemas, queries, mutations, and resolvers. There’s also a section touching on using Typescript with Node.js.

    Key Themes and Ideas:

    1. Node.js Basics & Execution:
    • Node.js allows execution of JavaScript code outside of a web browser environment.
    • Code can be executed directly in the terminal using node <filename.js>.
    • Synchronous code executes line by line. Asynchronous operations (like setTimeout) don’t block the execution of subsequent lines. “See this actually wait until unless this set timeout is getting run right so first time you’re getting this last line of the sync code and then after 2 seconds you’re getting that this message is delayed by 2 seconds.”
    1. Module System:
    • Node.js has a module system for organizing code into reusable pieces. “nodejs has a module system where you will be able to create different different modules and then you can use those modules in a single root module”
    • Each file is treated as a separate module. “each file again I’m repeating each file in nodejs will be treated as a separate modu okay”
    • module.exports is used to expose functionality from a module (similar to export in ES modules). “module. exports is used to expose functionality from a module”
    • require() is used to import functionality from other modules (similar to import). “require is used to import functionality from other modules as simple as that”
    • Node.js uses CommonJS module format.
    • Module wrapper: Every module is wrapped in a function before execution, providing variables like exports, require, module, __filename, and __dirname. “in nodejs every module whatever module that we are creating is wrapped in a function before it executed very very important thing and this rapper function we called as a module rapper function”
    • Demonstration of using module.exports and require to create and use a simple math module (first_module.js) in index.js.
    • Error handling using try…catch blocks. “to do this one right let’s go here okay first I’ll just minimize this one let’s create a very try and catch block now these all are also very basic JavaScript concept so we will take a try catch and catch will give us error right here”
    1. NPM (Node Package Manager):
    • NPM is the default package manager for Node.js. “npm is the default package manager for nodejs”
    • Allows installing and managing third-party libraries and tools.
    • Manages project dependencies. “this package.json file which is nothing but a Json file that contains a metadata about your project”
    • Enables running scripts defined in package.json.
    • Allows publishing your own packages.
    • Key NPM commands:
    • npm init: Initializes a new Node.js project, creating a package.json file. “to create a new package.json inside this folder first I’m going to open in our integrated terminal and let’s close everything and here to create it so we need to do npm it”
    • npm install <package_name>: Installs a specific package. “to do this one we need to use this npm install Command right so you do npm install and then the name of the package”
    • npm uninstall <package_name>: Uninstalls a package.
    • npm update <package_name>: Updates a package to the latest version.
    • npm run <script_name>: Runs a script defined in package.json. “to run a particular script so you can see that there is different different scripts right so you need to do npm run and then the script name and whatever scripts is defined in your package. JS and so that will be automatically run”
    • Distinction between dependencies (required for production) and devDependencies (needed for local development). “dependencies are all the packages that is actually required for your application to run in production”
    • “the D dependencies as the name suggest only needed for your local development and in right”
    1. Core Modules: Path and File System (fs)
    • Path Module: Provides utilities for working with file and directory paths. “path module provides utilities for working with file and directory paths”
    • path.dirname(__filename): Gets the directory name of the current file. “let’s log the current directory name so I’m going to do here console.log and let’s give like directory name right and here I’m going to give path dot so the um this is a method so this directory name and here you need to pass the file name so we’ll do file name”
    • path.basename(__filename): Gets the base name (filename) of the current file.
    • path.extname(__filename): Gets the file extension.
    • path.join(): Joins multiple path segments into one. “I’ll create one more Sal const join path and here we are going to give path. join and you can give different path let’s I want to go to/ user and then after this I want to merge or join documents this is just example”
    • path.resolve(): Resolves a sequence of paths to an absolute path.
    • path.normalize(): Normalizes a path string.
    • File System (fs) Module: Provides APIs for interacting with the file system. “the file system help you to work with files”
    • fs.existsSync(): Checks if a file or directory exists synchronously. “I’m going to check at this FS dot so we have exists sync okay so this here we’re going to check this data folder so this will check whether this is exist or not”
    • fs.mkdirSync(): Creates a directory synchronously. “fs. mkd sync now what again this will do this will create a that data folder right so I’m going to create pass your data folder and I’m going to just do a console.log and I’ll do data folder created”
    • fs.writeFileSync(): Writes data to a file synchronously. ” to create a file we are going to again you need to give the file path like where you want to create the file”
    • fs.readFileSync(): Reads data from a file synchronously.
    1. Asynchronous Programming:
    • Promises: Represents the eventual completion (or failure) of an asynchronous operation. “promise interface that we can use but let’s uh do this one with a simple example so I’m going to create a function I’m I’m going to do a delay function which will take a timer or time and this delay function will return return a promise”
    • States: Pending, Fulfilled (Resolved), Rejected.
    • .then(): Handles the fulfilled (resolved) state of a Promise. “this will give a DOT then right which I’m pretty sure you already know I’m you guys might be thinking that what I’m doing all of this but I think it’s important to just revise all of this one more time even if you know right so this will give you then which if the promise is getting resolv so it will come inside this then block or on full field”
    • .catch(): Handles the rejected state of a Promise. ” I’m going to catch here so this will be my error block and here I’m going to just log my error and let’s do a console do log and I’m going to log my error here”
    • Async/Await: Syntactic sugar over Promises, making asynchronous code easier to read and write. “asnc function that whatever each and every asnc function that you’ll be creating it will always always return a promise very very important every time it will return a promise”
    • async keyword: Marks a function as asynchronous; it implicitly returns a Promise. “I’m going to do as sync function right because we need to give the ASN keyword”
    • await keyword: Pauses the execution of an async function until a Promise is resolved. “the a keyword is is only be used inside your Hing function you can’t use outside of it right and what that a keyword does so it pauses the execution of the function until unless your promise is getting resolved”
    • Example of creating a delay function using setTimeout and Promises, and then using async/await to call it.
    1. Basic HTTP Server:
    • Using the http module to create a basic HTTP server.
    • Handling requests and sending responses.
    • Setting response headers.
    • Example of creating a simple server that responds with “Hello Node!” based on different routes.
    1. MongoDB and Mongoose:
    • Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
    • It provides a higher-level abstraction for interacting with MongoDB.
    • Connecting to MongoDB:Using mongoose.connect() to establish a connection to the database. Requires a connection string (MongoDB URI).
    • Error handling for connection failures.
    • Defining Schemas:Using mongoose.Schema to define the structure of documents in a MongoDB collection. “if you go here first you need to create a schema right so this mongos will give you this schema property and using this you’ll be able to create a new schema so you can see that new schema and then all the properties”
    • Defining data types for each field in the schema (e.g., String, Number, Boolean, Date, Array).
    • Setting validation rules (e.g., required, unique). “I want to tell mongos that okay this user the whatever public will come to register in your website the enam can be only a user so it can be only a normal user or it can be a admin user”
    • Setting default values for fields.
    • Creating Models:Using mongoose.model() to create a model based on a schema. “this will be mongus now to create a model you need to give a model and this will take a name okay this will take a name which will be this in your database it will be stored in that particular name whatever name you give let’s say you give this one as user so this will be the collection name in your database that I I’m storing all my user in this user collection”
    • Performing CRUD Operations (Create, Read, Update, Delete):create(): Creates a new document in the database.
    • find(): Retrieves documents from the database.
    • findById(): Retrieves a document by its ID.
    • updateOne(): Updates a document in the database.
    • deleteOne(): Deletes a document from the database.
    • Querying Data:Using query operators (e.g., $gt for greater than, $lt for less than, $in for inclusion in an array) to filter data.
    • Using logical operators (e.g., $and, $or) to combine multiple conditions.
    • Sorting data using sort().
    • Limiting the number of results using limit().
    • Pagination using skip() and limit().
    • Aggregation:Using the aggregation pipeline to perform complex data transformations. “this will be aggregation right and this aggregations pipeline actually is a concept from mangos where we can do a different set of things”
    • $match: Filters documents based on specified criteria.
    • $group: Groups documents based on a specified field and performs calculations (e.g., average, sum, count) on the grouped data.
    • $project: Selects specific fields to include in the output documents.
    1. Project Structuring:
    • Importance of organizing code into a well-defined folder structure. “till this part we haven’t worked on proper folder structure right each and everything like we have created inside server.js but that is not the way so how we are going to manage our project”
    • Common folder structure:
    • database: Contains database connection logic (db.js).
    • models: Contains Mongoose models (schemas).
    • routes: Defines API routes. “each and so for example let’s say you’re having a very complex application uh where you’re having multiple you need to work with multiple collection let’s say some e-commerce project so you’ll be having products you’ll be having card you’ll be having checkout you’ll be product details so for each and everything you’ll be having different different routes so that you’re not going to write each and everything on one single file and it will become messy so that is the reason we’ll be having a routes folder right”
    • controllers: Handles the main code logic for each route, interacting with the database. “controllers basically handle our main code logic that corate or basically connect with sorry not connect that uh work with your mongod database and then that controller we are going to use inside our outs”
    • middleware: Contains middleware functions. “whatever middleware related Logics that we’ll be writing we are going to write inside that folder”
    • helper: Contains helper/utility functions.
    • .env: Stores environment variables (e.g., database URI, API keys). “why we need the NV file let’s say the mongod the mongodb URL or let’s say some sensitive information some token and everything whatever we’ll be using in our project we are not going to push those changes in our GitHub right”
    • Using .gitignore to exclude sensitive files (e.g., .env, node_modules) from version control.
    1. Authentication and Authorization:
    • JWT (JSON Web Token):Using JWT for user authentication. “we need to authenticate every request by by passing a JWT token and then check if it’s a authenticated or not”
    • Generating a JWT upon successful login. “if those condition meets then we create our GWT token so that can access their route that’s it now this is like a very simple but the whole entire work how the authentication and authorization work behind the scene it”
    • Verifying the JWT in middleware to protect routes. “it that okay this will be a our security so we’ll be passing something and based on that we be able to check the data”
    • jsonwebtoken library for creating and verifying JWTs.
    • bcrypt.js:Hashing passwords before storing them in the database. “we need to has it or we need to store in encrypted form so that is the reason we’re going to use this most used package and that is called the bcrypt JS what this does you can see that it will create a Sol to protect against your Rainbow table attacks”
    • Comparing hashed passwords during login.
    • Using bcrypt.hash() to hash a password.
    • Using bcrypt.compare() to compare a password with its hash.
    • Role-Based Access Control (RBAC):Implementing RBAC to restrict access to certain routes based on user roles (e.g., admin, user). “So role based authentication or access control actually means what let’s say if there is a admin panel so you can only able to see if you are an admin user okay if you are a normal user it might be you’re not able to see”
    • Adding a role field to the user schema.
    • Creating middleware to check user roles before granting access to routes.
    1. File Uploads with Multer:
    • Using Multer middleware to handle file uploads.
    • Configuring Multer to specify the storage location for uploaded files.
    • Handling single and multiple file uploads.
    • Storing file information in the database.
    • Cloudinary is an option for file storage
    1. Testing with Jest:
    • Using Jest for writing unit tests. “let’s see that we’re going to how we are going to write some test okay so we’re going to use J and also the super test right and using these two package we we are going to write API test now as I already told you that what the unit test unit tests actually helps you to create the test for each and individual method not method each and individual modules it will not trigger any other modules it just want to test a single unit that’s what it”
    • Writing test cases to verify API endpoints.
    • supertest for sending HTTP requests to the API during testing.
    • Using expect() to make assertions about the response.
    1. Deployment (Render and Vercel):
    • Deploying Node.js applications to cloud platforms like Render and Vercel.
    • Render:Creating a render.yaml file to configure the deployment.
    • Specifying the build command and start command in the render.yaml file.
    • Setting environment variables in the Render dashboard.
    • Vercel:Configuring the build and output options in the Vercel dashboard.
    • Setting environment variables in the Vercel dashboard.
    • Importance of modifying package.json to ensure correct deployment.
    1. GraphQL:
    • GraphQL is a query language for APIs (developed by Facebook). “graph kill is developed by Facebook and uh this is nothing just a query language for apis”
    • Advantages over REST:
    • Precise data fetching: Clients can request only the data they need.
    • Single endpoint for all data operations.
    • Improved performance due to reduced over-fetching and under-fetching.
    • Key GraphQL concepts:
    • Schema: Defines the structure of the data and the operations that can be performed. “the schema file will Define your schema for your project that you are creating now what actually that schema is that is nothing but the structure of your data or the operation that you will perform”
    • Types: Define the data types of the fields in the schema (e.g., String, Int, Float, Boolean, ID). “this type keyword you need to give and then the name so let’s give this one as product so this is your type now inside this you need to specify that what kind of fields this product will have”
    • Queries: Used to fetch data.
    • Mutations: Used to modify data (create, update, delete). “mutation is where we’ll be able to create create a new product”
    • Resolvers: Functions that provide the data for the fields in the schema. “resolvers simply resolve what you are going to do so how you’re going to face the data”
    • Using graphql-tag to write GraphQL schemas and queries.
    1. TypeScript with Node.js:
    • Using TypeScript to add static typing to Node.js applications. “TypeScript is what it’s a superet of Javascript and that is actually what it has a static typing so whenever you’ll be creating projects you might uh or you usually wanted to write your function or the properties with a specific types”
    • Benefits of using TypeScript:
    • Improved code readability and maintainability.
    • Early detection of errors during development.
    • Better code completion and refactoring support in IDEs.
    • Defining interfaces to specify the types of objects. “you can create custom types remember I created this custom request and then I extend the request object from Express similarly for this one also you can extend the main document and then you can add your own Uh custom uh schemas or user structure whatever you you will be creating here”
    • Typing Mongoose schemas and models.

    Overall Impression:

    The text provides a broad overview of essential Node.js development concepts, ranging from basic syntax and module management to advanced topics like asynchronous programming, database interaction, testing, deployment, and GraphQL. The excerpts emphasize the importance of code organization, proper error handling, and understanding the underlying principles of each technology.

    Node.js Development: Frequently Asked Questions

    Frequently Asked Questions about Node.js Development

    Here are some frequently asked questions, based on the provided documentation.

    1. What is the Node.js module system, and why is it important?

    The Node.js module system allows you to organize your code into reusable pieces. Instead of writing all code into one large file, you can break it down into separate modules (files). This modularity makes code more manageable, readable, and reusable, particularly in large applications. Each file in Node.js is treated as a separate module. The module system relies on module.exports (to expose functionality from a module) and require (to import functionality from other modules).

    2. How do module.exports and require work in Node.js?

    module.exports is used to expose functions, objects, or values from a Node.js module, making them available for use in other modules. Think of it like ‘export’ in ES modules. require is used to import the functionality that has been exposed by other modules via module.exports. It’s similar to ‘import’ in ES modules, but follows the CommonJS syntax used by Node.js. When you require a module, you get whatever was assigned to module.exports in that module.

    3. What is the module wrapper in Node.js?

    In Node.js, every module’s code is wrapped inside a function before execution. This wrapper function provides several arguments: exports, require, module, __filename (the current file’s name), and __dirname (the current directory’s name). This wrapper provides a level of privacy and encapsulation for the module’s code, preventing variables and functions from polluting the global scope.

    4. What is npm (Node Package Manager), and what are some essential commands?

    npm is the default package manager for Node.js. It allows you to install, manage, and publish Node.js packages (libraries and tools). Key npm commands include:

    • npm init: Initializes a new Node.js project and creates a package.json file. Using npm init -y automatically accepts the defaults and creates a package.json file without prompting for input.
    • npm install <package_name>: Installs a specific package as a dependency for your project.
    • npm uninstall <package_name>: Uninstalls a package from your project.
    • npm update <package_name>: Updates a package to the latest version.
    • npm run <script_name>: Runs a script defined in the package.json file.

    5. What is the purpose of package.json?

    The package.json file is a JSON file that contains metadata about your Node.js project. It lists project dependencies (packages required for the application to run), development dependencies (packages needed only for development, like testing tools), scripts (commands to automate tasks), and other project-related information.

    6. How does the path module in Node.js help with file paths?

    The path module provides utilities for working with file and directory paths. It offers functions to:

    • Get the directory name of a file (path.dirname()).
    • Extract the base name (file name) from a path (path.basename()).
    • Get the file extension (path.extname()).
    • Join multiple path segments into a single path (path.join()).
    • Resolve a path to an absolute path (path.resolve()).
    • Normalize a path to remove redundant separators (path.normalize()).

    7. How do you handle asynchronous operations in Node.js using Promises, async, and await?

    • Promises: Promises represent the eventual result of an asynchronous operation. They can be in one of three states: pending, fulfilled (resolved), or rejected. Promises provide a structured way to handle asynchronous code, avoiding callback hell. You can use .then() to handle successful resolutions and .catch() to handle rejections.
    • Async/Await: async and await are syntactic sugar over Promises, making asynchronous code look and behave more like synchronous code. An async function always returns a Promise. The await keyword can only be used inside an async function and pauses the execution of the function until a Promise is resolved or rejected. This makes asynchronous code easier to read and write.

    8. How can you connect to a MongoDB database using Mongoose and define a schema?

    First, install the Mongoose package (npm install mongoose). Then, use mongoose.connect() to connect to your MongoDB database, providing the connection URL. After the connection is successful, define a schema using new mongoose.Schema(), specifying the data types and properties for each field in your documents. Then use mongoose.model() to create a model. This model allows you to interact with your MongoDB database collection using Mongoose’s methods (e.g., find(), create(), save(), delete(), aggregate())

    Node.js Custom Event Emitter Guide

    A custom event emitter can be created in Node.js using the events module. Here’s how it works:

    1. Import the events module.
    • This module is required to create event emitters.
    • const eventEmitter = require(‘events’).
    1. Create a class that extends EventEmitter.
    • This class will serve as the custom event emitter.
    • It inherits the emit and on methods from the EventEmitter class.
    • class MyCustomEmitter extends eventEmitter {
    • constructor() {
    • super();
    • this.greeting = ‘Hello’;
    • }
    • greet(name) {
    • this.emit(‘greeting’, this.greeting, name);
    • }
    • }
    1. Define a constructor.
    • The constructor can be used to set up initial properties for the emitter.
    • It calls super() to invoke the constructor of the parent class (EventEmitter).
    • In the example, the greeting property is initialized.
    1. Create a method to emit events.
    • This method uses the emit method to trigger an event with a specific name.
    • It can also pass arguments to the listeners.
    • In the example, the greet method emits a greeting event with the greeting and a name.
    1. Create an instance of the custom emitter.
    • This creates an object that can emit and listen for events.
    • const myCustomEmitter = new MyCustomEmitter();
    1. Register a listener for the event.
    • The on method is used to register a listener function that will be executed when the event is emitted.
    • The listener function receives the arguments passed by the emit method.
    • myCustomEmitter.on(‘greeting’, (greeting, name) => {
    • console.log(‘Greeting event:’, greeting, name);
    • });
    1. Emit the event.
    • Call the method that emits the event to trigger the listener function.
    • myCustomEmitter.greet(‘Sumit’);

    When the code is executed, the greet method emits the greeting event. This triggers the listener function, which logs “Greeting event: Hello Sumit” to the console.

    Creating an Express Server in Node.js

    An Express server in Node.js can be created as follows.

    Key Features of Express.js

    • Routing: Express.js is known for its routing capabilities.
    • Middleware: It uses middleware.
    • Template Engines: It supports template engines like EJS and Pug for dynamic HTML generation.
    • Static File Serving: It can serve static files.
    • Error Handling: It offers error handling.
    • RESTful API Development: It is useful for creating RESTful APIs.

    Steps to Create an Express Server

    1. Import the Express module: This is done using the require function.
    2. const express = require(‘express’);
    3. Create an Express application: Invoke the express module which returns an express application.
    4. const app = express();
    5. Define a port to listen for client requests.
    6. const port = 3000;
    7. Create routes: Define routes for different HTTP methods (GET, POST, etc.) and URL paths.
    8. app.get(‘/’, (req, res) => {
    9. res.send(‘Hello World!’);
    10. });
    • The app.get() method specifies a route for handling GET requests to the root URL (“/”).
    • The callback function receives a request object (req) and a response object (res).
    • The res.send() method sends the response “Hello World!” back to the client.
    1. Start the server: Use the app.listen() method to start the server and listen for incoming connections on a specific port.
    2. app.listen(port, () => {
    3. console.log(`Server is running at port ${port}`);
    4. });
    • This makes the server accessible at localhost:3000.

    Middleware

    • To use middleware, the app.use() method is employed.
    • Middleware functions have access to the request and response objects, and the next middleware function in the stack.
    • express.json() is a built-in middleware used to parse JSON data in request bodies.

    Application Settings

    • app.set() is used to set application-level settings, such as the view engine.
    • For example, to set the view engine to EJS:
    • app.set(‘view engine’, ‘ejs’);

    Example

    const express = require(‘express’);

    const app = express();

    const port = 3000;

    app.get(‘/’, (req, res) => {

    res.send(‘Hello World!’);

    });

    app.listen(port, () => {

    console.log(`Server is running at port ${port}`);

    });

    Express.js Dynamic Routing

    Dynamic routing in Express.js involves creating routes where a portion of the URL can vary. This allows a single route to handle requests for multiple resources based on a parameter passed in the URL.

    Key Concepts and Implementation

    • Defining Dynamic Routes: To create a dynamic route, a colon (:) is used before the parameter name in the route path. For example, /products/:id defines a route where :id is a dynamic parameter.
    • Accessing Route Parameters: The req.params object is used to access the values of the dynamic parameters. For example, in the route /products/:id, the value of id can be accessed using req.params.id.
    • Example:
    • app.get(‘/products/:id’, (req, res) => {
    • const productID = parseInt(req.params.id); // Parse the ID
    • // Logic to retrieve product from a database or array
    • // Send the product as a JSON response
    • });

    Note: Information regarding retrieving a product from a database or array was not found in the source.

    Use Cases

    • E-commerce Applications: Dynamic routes are commonly used in e-commerce to display details for specific products. For example, clicking on a product with id2 would navigate to /products/2.
    • API Endpoints: They are useful for creating API endpoints where a specific resource needs to be accessed based on its ID or another identifier.

    Important Notes

    • Parameter Naming: When defining dynamic routes, the name given to the parameter after the colon (e.g., :id) must be used to access its value in req.params (e.g., req.params.id).
    • Data Retrieval: In real-world scenarios, the dynamic value captured from the URL is often used to query a database and retrieve the corresponding data.
    • Middleware: Dynamic routes can also be used with middleware to perform actions based on the parameters.

    By using dynamic routing, Express.js applications can create more flexible and efficient routes that adapt to different request parameters.

    Express.js Template Engines for Dynamic HTML Generation

    Template engines in Express.js are used to generate dynamic HTML pages with plain JavaScript. Template engines can help to generate dynamic HTML pages in Express applications.

    Key Aspects

    • Definition: A template engine is HTML markup with plain JavaScript.
    • Purpose: Template engines help in generating dynamic HTML pages in Express applications.

    Example with EJS

    • Set the View Engine: Tell Express to use EJS as the view engine.
    • app.set(‘view engine’, ‘ejs’);
    • Set the Views Directory: Specify the directory where the view files are located.
    • app.set(‘views’, path.join(__dirname, ‘views’));
    • Create Views: Create a views folder where the HTML files will reside. Each file in this folder will be treated as a separate module.
    • Render Views: Use res.render() to render the template and pass data to it.
    • app.get(‘/’, (req, res) => {
    • res.render(‘home’, { title: ‘Home’, products: products });
    • });
    • In this example, home.ejs is rendered, and data such as title and products are passed to the template.
    • Access Data in Templates: Use special tags to output dynamic values in the template.
    • <h1><%= title %></h1>
    • <ul>
    • <% products.forEach(product => { %>
    • <li><%= product.title %></li>
    • <% }); %>
    • </ul>
    • The <%= … %> tag is used to output the value of a variable.
    • The <% … %> tag is used for control flow, such as loops.

    Benefits of Using Template Engines

    • Dynamic HTML: Template engines allow generating HTML pages dynamically based on data from the server.
    • Code Reusability: Common components, like headers and footers, can be created as partials and included in multiple views.

    By using template engines like EJS, developers can create dynamic and maintainable web applications with Express.js.

    RESTful API Development with Express.js: A Practical Guide

    RESTful API development involves creating APIs that adhere to the principles of REST (Representational State Transfer) architecture. Express.js is a framework that provides features for building such APIs in Node.js.

    Key Features of Express.js for API Development

    • Routing: Manages routes.
    • Middleware: Uses middleware.
    • RESTful API Development: Facilitates RESTful API creation.

    Project Structure

    To organize an API project, a typical structure includes:

    • Models: Data models for interacting with the database.
    • Controllers: Logic for handling requests and responses.
    • Routes: Defines the API endpoints.

    Steps to Build a RESTful API

    1. Set up the project: Create a new Node.js project and initialize package.json.
    2. npm init -y
    3. Install Express.js: Install Express.js and any other required packages such as body-parser.
    4. npm install express
    5. Create the main application file: Create app.js (or a similar name) to set up the Express server.
    6. Require Express: Import the Express module.
    7. const express = require(‘express’);
    8. Create an Express application: Invoke express to create an application.
    9. const app = express();
    10. Define middleware: Use middleware to parse JSON data.
    11. app.use(express.json());
    12. Define routes: Create routes for different API endpoints.
    • GET: Retrieve data.
    • app.get(‘/api/books’, (req, res) => {
    • // Logic to get all books
    • });
    • app.get(‘/api/books/:id’, (req, res) => {
    • // Logic to get a single book by ID
    • });
    • POST: Create new data.
    • app.post(‘/api/books’, (req, res) => {
    • // Logic to add a new book
    • });
    • PUT: Update existing data.
    • app.put(‘/api/books/:id’, (req, res) => {
    • // Logic to update a book
    • });
    • DELETE: Delete data.
    • app.delete(‘/api/books/:id’, (req, res) => {
    • // Logic to delete a book
    • });
    • Dynamic routes can be created using colons to define parameters.
    1. Start the server: Specify the port and start listening.
    2. const port = 3000;
    3. app.listen(port, () => {
    4. console.log(`Server is running on port ${port}`);
    5. });

    Testing APIs with Postman

    • Install Postman: Download and install Postman for testing API endpoints.
    • Create requests: Set up requests in Postman to test each route.
    • Specify the type (GET, POST, PUT, DELETE).
    • Enter the URL.
    • Include any required headers or body data.
    • Send requests and verify responses: Send the requests and verify that the responses are as expected.

    By following these steps, you can create a RESTful API using Express.js, organize the project structure, and test the API endpoints with Postman.

    Node JS Full Course 2024 | Complete Backend Development Course | Part 1

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