In every programming language you will find some primitives values. It's not different in JavaScript, we have 7- number, string, boolean, bigint, null, undefined and symbol. Every one having a different case usage. In this article I gonna show you every Javascript primitive values and its usage case, but first what is a primitive value? ## Definition In Javascript, a data type is considered primitive value if immutable and is not an object and has no methods or properties. You can never change a primitive value in Javascript, for example: ```js let a = 'hello' let b = a console.log(b) // "hello" b.substring(2) // "llo" console.log(b) // "hello" console.log(a) // "hello" let c = [3] let d = c c.push(1) console.log(c) // Array [ 3, 1 ] console.log(d) // Array [ 3, 1 ] ``` In the example above, we can never change the primitive value string *hello* no matter how many methods we do in *b*, but is not the case of array *c* and *d*, when we push item to *d*, automatically pushes to *c* too, so is mutable. Primitives values are super important to know, independently of the language used, every one has a critical importance and usage case. For this reason, we're gonna explain each one that exists in JavaScript. ## type number In JavaScript, **Number** is a primitive data type used to represent numerical values. It stores 64-bit floating-point numbers following the IEEE 754 standard, which supports double-precision. This makes it versatile for handling integers as well as decimals, and it's the primary type for representing numbers in JavaScript. Number accepts almost all operators. An interesting fact is that JavaScript handles somethings that would be consider error in other programming languages, we will see more in the next topics. An important aspect of numbers in JavaScript is that when you perform an operation that is not possible, such attempting invalid operations between types (like multiplying strings), the result will be *NaN*, which stands for 'Not a Number' and indicates an error in the computation. ```js const n = 1 const n2 = 2 console.log(n + n2) // 3 console.log(n - n2) // -1 console.log(n * n2) // 2 console.log(n / n2) // 0.5 console.log(n % n2) // 1 console.log(n === n2) // false console.log('text' * 'text') // NaN ``` ## type string A **String** is a sequence of characters used to represent text in JavaScript. It allows for the storage and manipulation of textual data, making it essential for handling words, sentences, and other character-based information. Strings have a wide range of use cases due to their versatility in representing and manipulating text, making them one of the most frequently used data types in JavaScript. JavaScript has a particularly behavior- If you use the sum operator with some string there will be no error as would happen in other programming languages, instead JavaScript handle this by transforming the result in a string by concatenating the values. ```js const s = '1' const s2 = 'text' console.log(1 + s) // 11 console.log(false + s2) // falsetext ``` ## bigint **BigInt** is used to store integers beyond JavaScript's safe integer limit (Number.MAX_SAFE_INTEGER). While powerful for handling very large numbers, it is rarely needed in typical small-medium applications. ```js const maxSafeNumber = Number.MAX_SAFE_INTEGER // 9007199254740991 const beyondMaxN1 = maxSafeNumber + 1 // 9007199254740992 const beyondMaxN2 = maxSafeNumber + 2 // 9007199254740992 const bigN = 9007199254740991n const beyondMaxBigN = 9007199254740991n + 2n // 9007199254740993n ``` ## boolean A **Boolean** is a logical data type that can only hold one of two values: *true* or *false*. It is commonly used in conditions and decision-making statements. Those values can be represented in other forms like binary, 1 represents true and 0 represents false. This means that, in Javascript you can make operations with those values. ```js const isDeveloper = true const isLastType = false console.log(true + 2) // 3 console.log(true - 2) // -1 ``` ## undefined **undefined** is a default value automatically assigned to variables that have been declared but not yet given a value, or to function parameters that have no corresponding arguments. ```js let value const value2 = undefined ``` ## symbol A **Symbol** is a unique and immutable primitive value that can be used as a key for properties in an object, ensuring property names do not conflict. ```js const sym1 = Symbol() const sym2 = Symbol('desc') const sym3 = Symbol('desc') console.log(sym2 === sym3) // false ``` ## null A **null** value represents a reference that intentionally points to a nonexistent or invalid object or address, indicating the absence of any value. In operations, you can treat null as 0 since many calculations can be performed by substituting null with 0 without affecting the outcome. ```js const value = null console.log(2 + null) // 2 console.log(2 * null) // 2 ``` ## Conclusion In this article we saw all the primitive data types that exists in JavaScript. This article was short, but I hope you like it. Have a nice day. 😎✨✨✨😎
Did you know what is morse code? It is a method of communication using short and long signals that are common represented as dots and dashes. Developed to transmit human language to math language and as only translate letters it became and international standard. ## Short Answer To create a morse code encrypter and decrypter you have two methods. One can use the [ASCII table](https://www.lookuptables.com/text/ascii-table) as described in this [answer of Stackoverflow](https://stackoverflow.com/a/26059284). But my preferred way is making a dictionary mapping all valid characters, which would be letters A from Z, number 0 to 9 and a blank space to separate words, anything else would be `undefined` and you can handle as you want. 1. Create a dictionary containing all valid characters: ```typescript const dictionary = { 'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', ' ': '/' } ``` 2. Add function to transform letters into morse code: ```typescript function transformToMorse(rawText: string) { return rawText.split('').map(letter => dictionary[letter.toLowerCase()]).join(' ') } ``` --- ## Long Answer ### What is morse code? Morse code was created by [Samuel Morse](https://en.wikipedia.org/wiki/Samuel_Morse) and [Alfred Vail](https://en.wikipedia.org/wiki/Alfred_Vail). It is a method to encode human words characters into just short and long sequences that can be anything from lights, sounds, smoke, anything you can make a short or long signal can be used to represent any word or number from *a-z* and *0-9*. It became very popular in telegraph - grandfather of communication that used morse code to transmit messages from short and long bip. They even had a profession to people hearing and translating the messages- [telegraphist](https://en.wikipedia.org/wiki/Telegraphist). Morse code works by using a [sequence of short or long signal](https://en.wikipedia.org/wiki/Morse_code) to represent one letter/number. For example, the letter **t** can be represent by a long signal **-**, but the letter **g** is two long signal and one short signal **--.**. With this you can make a very good system of communication to transform human language into natural language. It's also very popular on pop culture as almost every riddle movie has a part using morse to encrypt or decrypt some kind of message. ### Alphabet |Character | Morse Equivalent| |----|----| | 0 | ----- | | 1 | .---- | | 2 | ..--- | | 3 | ...-- | | 4 | ....- | | 5 | ..... | | 6 | -.... | | 7 | --... | | 8 | ---.. | | 9 | ----. | | a | .- | | b | -... | | c | -.-. | | d | -.. | | e | . | | f | ..-. | | g | --. | | h | .... | | i | .. | | j | .--- | | k | -.- | | l | .-.. | | m | -- | | n | -. | | o | --- | | p | .--. | | q | --.- | | r | .-. | | s | ... | | t | - | | u | ..- | | v | ...- | | w | .-- | | x | -..- | | y | -.-- | | z | --.. | ### Google learn morse If you stay curious to learn more about morse code, I highly recommend you try [Google's morse learn](https://morse.withgoogle.com/learn). They use images to help us remember the letters. <Img src="https://github.com/fescherer/blog/assets/62115215/65e73bb9-c4a8-4316-9391-a001b0d77d2a" source="https://kpronline.com/blog/learn-morse-code-with-the-morse-typing-trainer" name="Code cues used in the Morse Typing Trainer" alt="List of all codes cues used in morse typing trainer" /> ### Javascript/Typescript functions To create a morse code encrypter and decrypter you have two methods. - Using ASCII table You can use the [ASCII table](https://www.lookuptables.com/text/ascii-table) as described in this [answer of Stackoverflow](https://stackoverflow.com/a/26059284). By knowing that ASCII table characters *a - z* goes from *97* to *122* and numbers *0 - 9* goes from *48* to *57* you can do something like this. 1. First create 2 arrays containing the characters and one constant for the space. ```typescript // Characters in order A - Z and 0 - 9 const charactersAZ = ['.-', '-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..'] const numbers09 = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.'] const characterSpace = '/' ``` 2. Now you need to remove all weird characters that does not have an index on our arrays ```typescript function cleanRawText(rawText: string) { return rawText.toLowerCase().replace(/[^a-z0-9\s]/g, ""); } ``` 3. Finally make a function to return the encrypted character. ```typescript const isNumberRegex = /^\d+$/ function transformToMorse(rawText: string) { const formatText = cleanRawText(rawText); return formatText.split('').map(letter => { if(letter === " ") return characterSpace; asciiCode = letter.charCodeAt(letter); if(isNumberRegex.test(letter)) return numbers09[asciiCode - 48]; else return charactersAZ[asciiCode - 97]; }).join(' '); } ``` 4. Test the functions ```typescript transformToMorse('Hello world') // result .... . .-.. .-.. --- / .-- --- .-. .-.. -.. ``` -Using dictionary My preferred way is making a dictionary mapping all valid characters, which would be letters A from Z, number 0 to 9 and a blank space to separate words, anything else would be `undefined` and you can handle as you want. 1. Create a dictionary containing all valid characters: ```typescript const dictionary = { 'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', ' ': '/' } ``` 2. Add function to transform letters into morse code: ```typescript function transformToMorse(rawText: string) { return rawText.split('').map(letter => dictionary[letter.toLowerCase()]).join(' ') } ``` 3. Test it ```typescript transformToMorse('Hello world') // result .... . .-.. .-.. --- / .-- --- .-. .-.. -.. ``` Which one of them should I choose? Well, I think is up to you, personally I will not go to performance side because both has `map` method and the others doesn't make that much difference. I would choose based on readability as the first one the arrays seems a bit confusing and object making a dictionary seems much more readable for me. Okay, but this is only an encrypter, where is the decrypter? For this, just invert the logic, make a dictionary containing morse code as keys, letters with values and the backslash for white space. ### Bonus: UI - NextJS - Tailwind This article only shows how to convert, but not how to create an application with these logics. I'am gonna leave this for you to create a design. I personally recommend to create a [NextJS](https://nextjs.org/docs/getting-started/installation) project with [TailwindCSS](https://tailwindcss.com/docs/installation) for styling and [Vercel](https://vercel.com) as free host. [You can checkout the source code to get inspired](https://github.com/fescherer/morse-secret-scripter) <Img src="https://github.com/fescherer/blog/assets/62115215/e3c04fd3-5140-484a-8063-541abe46f66f" source="https://morse-secret-scripter.felipescherer.com" name="Morse secret scripter home page" alt="Home page of morse secret scripter containing input and output text areas for encrypt and decrypt" /> ### Conclusion In this article you learnt the history of morse code and how to create simple functions to translate/encrypt/decrypt morse code using Javascript/Typescript. Feel free to leave any suggestions, corrections and tips. Thank you for reading and see you in the next article. Have a nice day. 😎✨✨✨😎