Tumgik
#array in javascript
watchmorecinema · 11 months
Text
Normally I just post about movies but I'm a software engineer by trade so I've got opinions on programming too.
Apparently it's a month of code or something because my dash is filled with people trying to learn Python. And that's great, because Python is a good language with a lot of support and job opportunities. I've just got some scattered thoughts that I thought I'd write down.
Python abstracts a number of useful concepts. It makes it easier to use, but it also means that if you don't understand the concepts then things might go wrong in ways you didn't expect. Memory management and pointer logic is so damn annoying, but you need to understand them. I learned these concepts by learning C++, hopefully there's an easier way these days.
Data structures and algorithms are the bread and butter of any real work (and they're pretty much all that come up in interviews) and they're language agnostic. If you don't know how to traverse a linked list, how to use recursion, what a hash map is for, etc. then you don't really know how to program. You'll pretty much never need to implement any of them from scratch, but you should know when to use them; think of them like building blocks in a Lego set.
Learning a new language is a hell of a lot easier after your first one. Going from Python to Java is mostly just syntax differences. Even "harder" languages like C++ mostly just mean more boilerplate while doing the same things. Learning a new spoken language in is hard, but learning a new programming language is generally closer to learning some new slang or a new accent. Lists in Python are called Vectors in C++, just like how french fries are called chips in London. If you know all the underlying concepts that are common to most programming languages then it's not a huge jump to a new one, at least if you're only doing all the most common stuff. (You will get tripped up by some of the minor differences though. Popping an item off of a stack in Python returns the element, but in Java it returns nothing. You have to read it with Top first. Definitely had a program fail due to that issue).
The above is not true for new paradigms. Python, C++ and Java are all iterative languages. You move to something functional like Haskell and you need a completely different way of thinking. Javascript (not in any way related to Java) has callbacks and I still don't quite have a good handle on them. Hardware languages like VHDL are all synchronous; every line of code in a program runs at the same time! That's a new way of thinking.
Python is stereotyped as a scripting language good only for glue programming or prototypes. It's excellent at those, but I've worked at a number of (successful) startups that all were Python on the backend. Python is robust enough and fast enough to be used for basically anything at this point, except maybe for embedded programming. If you do need the fastest speed possible then you can still drop in some raw C++ for the places you need it (one place I worked at had one very important piece of code in C++ because even milliseconds mattered there, but everything else was Python). The speed differences between Python and C++ are so much smaller these days that you only need them at the scale of the really big companies. It makes sense for Google to use C++ (and they use their own version of it to boot), but any company with less than 100 engineers is probably better off with Python in almost all cases. Honestly thought the best programming language is the one you like, and the one that you're good at.
Design patterns mostly don't matter. They really were only created to make up for language failures of C++; in the original design patterns book 17 of the 23 patterns were just core features of other contemporary languages like LISP. C++ was just really popular while also being kinda bad, so they were necessary. I don't think I've ever once thought about consciously using a design pattern since even before I graduated. Object oriented design is mostly in the same place. You'll use classes because it's a useful way to structure things but multiple inheritance and polymorphism and all the other terms you've learned really don't come into play too often and when they do you use the simplest possible form of them. Code should be simple and easy to understand so make it as simple as possible. As far as inheritance the most I'm willing to do is to have a class with abstract functions (i.e. classes where some functions are empty but are expected to be filled out by the child class) but even then there are usually good alternatives to this.
Related to the above: simple is best. Simple is elegant. If you solve a problem with 4000 lines of code using a bunch of esoteric data structures and language quirks, but someone else did it in 10 then I'll pick the 10. On the other hand a one liner function that requires a lot of unpacking, like a Python function with a bunch of nested lambdas, might be easier to read if you split it up a bit more. Time to read and understand the code is the most important metric, more important than runtime or memory use. You can optimize for the other two later if you have to, but simple has to prevail for the first pass otherwise it's going to be hard for other people to understand. In fact, it'll be hard for you to understand too when you come back to it 3 months later without any context.
Note that I've cut a few things for simplicity. For example: VHDL doesn't quite require every line to run at the same time, but it's still a major paradigm of the language that isn't present in most other languages.
Ok that was a lot to read. I guess I have more to say about programming than I thought. But the core ideas are: Python is pretty good, other languages don't need to be scary, learn your data structures and algorithms and above all keep your code simple and clean.
13 notes · View notes
nishar-multani · 2 years
Text
4 notes · View notes
Text
youtube
0 notes
htmlcodegenerator · 1 month
Text
how to easily create JavaScript arrays and objects containing alphabet letters (a-z) lowercase (A-Z) uppercase and numeric values (0-9).
1 note · View note
jcmarchi · 1 month
Text
All About JavaScript Loops
New Post has been published on https://thedigitalinsider.com/all-about-javascript-loops/
All About JavaScript Loops
Every programming language has loops. Loops perform an operation (i.e., a chunk of work) a number of times, usually once for every item in an array or list, or to simply repeat an operation until a certain condition is met.
JavaScript in particular has quite a few different types of loops. I haven’t even used all of them, so for my own curiosity, I thought I’d do a high-level overview of them. And as it turns out, there are pretty good reasons I haven’t used at least a couple of the different types.
So, for now let’s spend a while exploring the different types of loops, what we can do with each of one, and why you might use one over another. (You’ll think that little play on words is absolutely hilarious by the end.)
The while and do...while loops
First up is the while loop. It’s the most basic type of loop and has the potential to be the easiest to read and the fastest in many cases. It’s usually used for doing something until a certain condition is met. It’s also the easiest way to make an infinite loop or a loop that never stops. There is also the do...while statement. Really, the only difference is that the condition is checked at the end versus the beginning of each iteration.
// remove the first item from an array and log it until the array is empty let queue1 = ["a", "b", "c"]; while (queue1.length) let item = queue1.shift(); console.log(item); // same as above but also log when the array is empty let queue2 = []; do let item = queue2.shift() ?? "empty"; console.log(item); while (queue2.length);
The for loop
Next is the for loop. It should be the go to way to do something a certain number of times. If you need to repeat an operation, say, 10 times, then use a for loop instead. This particular loop may be intimidating to those new to programming, but rewriting the same loop in the while-style loop can help illustrate the syntax make it easier to stick in your mind.
// log the numbers 1 to 5 for (let i = 1; i <= 5; i++) console.log(i); // same thing but as a while loop let i = 1; // the first part of a for loop // the second while (i <= 5) console.log(i); i++; // the third ("end");
The for...of and for await...of loops
A for...of loop is the easiest way to loop through an array.
let myList = ["a", "b", "c"]; for (let item of myList) console.log(item);
They aren’t limited to arrays though. Technically they can iterate through anything that implements what is called an iterable protocol. There are a few built-in types that implement the protocol: arrays, maps, set, and string, to mention the most common ones, but you can implement the protocol in your own code. What you’d do is add a [Symbol.iterator] method to any object and that method should return an iterator. It’s a bit confusing, but the gist is that iterables are things with a special method that returns iterators; a factory method for iterators if you will. A special type of function called a generator is a function that returns both a iterable and iterator.
let myList = *[Symbol.iterator]() yield "a"; yield "b"; yield "c"; , ; for (let item of myList) console.log(item);
There is the async version of all the things I just mentioned: async iterables, async iterators, and async generators. You’d use an async iterable with for await...of.
async function delay(ms) return new Promise((resolve) => setTimeout(resolve, ms); ); // this time we're not making an iterable, but a generator async function* aNumberAMinute() let i = 0; while (true) // an infinite loop yield i++; // pause a minute await delay(60_000); // it's a generator, so we need to call it ourselves for await (let i of aNumberAMinute()) console.log(i); // stop after one hour if (i >= 59) break;
One unobvious thing about for await...of statement is that you can use it with non-async iterables and it will work just fine. The reverse, however, is not true; you can’t use async iterables with the for...of statement.
The forEach and map loops
While these are not technically loops per se, you can use them to iterate over a list.
Here is the thing about the forEach method. Historically it was much slower than using a for loop. I think in some cases that may not be true anymore, but if performance is a concern, then I would avoid using it. And now that we have for...of I’m not sure there is much reason to use it. I guess the only reason that it still may come up is if you have a function ready to use as the callback, but you could easily just call that same function from inside the body of for...of.
forEach also receives the index for each item though, so that may be a thing you need too. Ultimately, the decision to use it will probably come down to whether any other code you’re working with uses it, but I personally would avoid using it if I’m writing something new.
let myList = ["a", "b", "c"]; for (let item of myList) console.log(item); // but maybe if I need the index use forEach ["a", "b", "c"].forEach((item, index) => console.log(`$index: $item`); );
Meanwhile, map essentially converts one array into another. It still has the same performance impact that forEach has, but it is a bit nicer to read than the alternative. It’s certainly subjective though, and just like with forEach you’ll want to do what the rest of your other code is doing. You see it a ton in React and React-inspired libraries as the primary way to loop through an array and output a list of items within JSX.
function MyList(items) return ( <ul> items.map((item) => return <li>item</li>; ) </ul> );
The for...in loop
This list of loops in JavaScript wouldn’t be complete without mentioning the for...in statement because it can loop through the fields of an object. It visits fields that are inherited through the object’s prototype chain too, though, and I’ve honestly always avoided it for that reason.
That said, if you have an object literal, then for...in might be a viable way to iterate through the keys of that object. Also it’s worth noting that if you’ve been programming JavaScript for a long time, you may remember that the order of keys use to be inconsistent between browsers, but now the order is consistent. Any key that could be an array index (i.e., positive integers) will be first in ascending order, and then everything else in the order as authored.
let myObject = a: 1, b: 2, c: 3, ; for (let k in myObject) console.log(myObject[k]);
Wrapping up
Loops are something that many programmers use every day, though we may take them for granted and not think about them too much.
But when you step back and look at all of the ways we have to loop through things in JavaScript, it turns out there are several ways to do it. Not only that, but there are significant — if not nuanced — differences between them that can and will influence your approach to scripts.
0 notes
juancerqueirabr · 3 months
Text
JavaScript oferece várias funções nativas para manipulação de arrays. Aqui estão algumas das mais comuns e úteis:
1. **`push` e `pop`**:
- `push`: Adiciona um ou mais elementos ao final do array.
- `pop`: Remove o último elemento do array.
```javascript
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
```
2. **`shift` e `unshift`**:
- `shift`: Remove o primeiro elemento do array.
- `unshift`: Adiciona um ou mais elementos no início do array.
```javascript
let arr = [1, 2, 3];
arr.shift(); // [2, 3]
arr.unshift(0); // [0, 2, 3]
```
3. **`concat`**:
- Junta dois ou mais arrays.
```javascript
let arr1 = [1, 2];
let arr2 = [3, 4];
let arr3 = arr1.concat(arr2); // [1, 2, 3, 4]
```
4. **`slice`**:
- Retorna uma cópia rasa de uma parte do array, sem modificar o array original.
```javascript
let arr = [1, 2, 3, 4];
let slicedArr = arr.slice(1, 3); // [2, 3]
```
5. **`splice`**:
- Adiciona/remova elementos de qualquer posição do array.
```javascript
let arr = [1, 2, 3, 4];
arr.splice(1, 2); // [1, 4]
arr.splice(1, 0, 2, 3); // [1, 2, 3, 4]
```
6. **`map`**:
- Cria um novo array com os resultados de uma função aplicada a cada elemento do array.
```javascript
let arr = [1, 2, 3];
let mappedArr = arr.map(x => x * 2); // [2, 4, 6]
```
7. **`filter`**:
- Cria um novo array com todos os elementos que passam no teste implementado pela função fornecida.
```javascript
let arr = [1, 2, 3, 4];
let filteredArr = arr.filter(x => x > 2); // [3, 4]
```
8. **`reduce`**:
- Aplica uma função a um acumulador e a cada elemento do array (da esquerda para a direita) para reduzi-lo a um único valor.
```javascript
let arr = [1, 2, 3, 4];
let sum = arr.reduce((acc, x) => acc + x, 0); // 10
```
9. **`find` e `findIndex`**:
- `find`: Retorna o primeiro elemento que satisfaz a função de teste.
- `findIndex`: Retorna o índice do primeiro elemento que satisfaz a função de teste.
```javascript
let arr = [1, 2, 3, 4];
let found = arr.find(x => x > 2); // 3
let foundIndex = arr.findIndex(x => x > 2); // 2
```
10. **`sort`**:
- Ordena os elementos do array e retorna o array.
```javascript
let arr = [4, 2, 3, 1];
arr.sort(); // [1, 2, 3, 4]
```
11. **`forEach`**:
- Executa uma função para cada elemento do array.
```javascript
let arr = [1, 2, 3];
arr.forEach(x => console.log(x)); // 1 2 3
```
Essas são algumas das principais funções de manipulação de array em JavaScript. Elas permitem realizar uma ampla gama de operações para trabalhar com dados de maneira eficiente e concisa.
0 notes
techpathshala · 4 months
Text
JavaScript Array Splice Method: A Detailed Exploration
0 notes
clonecoding-en · 10 months
Link
Efficient JavaScript with Spread Syntax
Mastering the Art of Efficient JavaScript with Spread Syntax
The spread syntax in modern JavaScript empowers developers to handle arrays and objects efficiently. This comprehensive article delves deep into the world of spread syntax, unveiling its versatile applications and addressing common pitfalls.
By exploring real-world scenarios and code examples, readers gain a profound understanding of how to leverage spread syntax for tasks such as merging arrays, copying objects, and passing dynamic arguments to functions. This article also equips developers with the knowledge to identify and troubleshoot errors that may arise when misusing spread syntax.
Navigating through the complexities of spread syntax, developers will learn how to write code that is not only concise and effective but also avoids common misconceptions and pitfalls. Whether you're new to JavaScript or an experienced developer, this article provides valuable insights into harnessing the power of spread syntax for optimal code efficiency and readability.
0 notes
clonecoding-ja · 10 months
Link
JavaScriptのスプレッド構文:ArrayとObjectsの効率的な操作方法
この記事は、現代のJavaScriptにおけるスプレッド構文の重要性と使用方法に焦点を当てています。スプレッド構文は、ArrayやObjectsの効率的な操作手法を提供し、コードの簡潔性と効率性を向上させます。記事はスプレッド構文の基本的な理解から、ArrayやObjectsにおける使用方法、一般的なエラーの解決策までを詳細に解説しています。
スプレッド構文を使うことで、ArrayやObjectsを展開し、結合する方法、オブジェクトのプロパティを効率的に操作する方法、関数引数として活用する方法などが具体的なコード例とともに説明されています。また、スプレッド構文の使用に伴う一般的なエラーやその解決策も紹介されており、読者はスムーズなプログラミング体験を得るためのポイントを押さえることができます。
この記事を通じて、読者はJavaScriptでスプレッド構文を使いこなすための手法やベストプラクティスを学び、ArrayやObjectsの操作を効率的に行うスキルを向上させることができるでしょう。
0 notes
fingertipsmp3 · 11 months
Text
The slides for class today look deceptively simple. Should I be concerned
#i realised that probably the reason i'm not doing great with class right now is i'm not really doing anything to prepare#other people in the class already have knowledge either because they've done this before or they know more javascript than me#(which is not hard since i don't know javascript)#but because i go in knowing nothing i just sort of fumble my way through and end up sitting there 2+ hours after the start of class#completely bamboozled and with my brain fried and no finished tasks to show for it#i get the work done eventually but i have to google thee most basic questions or rewatch segments of class (it is recorded thank god)#to understand it. which like.. don't get me wrong; i feel like if i was capable of paying attention better i'd probably understand it all#the first time around. my instructors are great. but i am not capable of paying attention#as soon as i don't understand something i just get confused and zone out instead of processing the information that would help me understan#it is soooo bad i hate it. so i was like okay. why don't i go through the slides first#read a couple of articles on this stuff and talk myself through the tasks. not DO them yet because i get plenty of time to do them tonight#we get like 15-20 minutes per task. sometimes half an hour if it's a big one#but making sure i understand how to do them will ensure i don't spend those 15-30 minutes having a breakdown#but with this one i was like... it looks okay???#i think my biggest problem irt coding is i can never remember the fucking syntax. like i'm well aware of HOW to do stuff#i know how to link a stylesheet or a script file to a html file i can just never remember the exact syntax#i always have to google it or look at a previous project i made (on which i googled it)#<link ref='stylesheet' href='styles.css'></link> and <script src='script.js'></script> right?? please tell me that's right#so it's like. do i know what a loop is? yes. do i know what an array is? yes. do i know what an object is? i think so#do i know how to make any of these? NO because i don't know the syntax!!!#it's upsetting lol. i really wonder if these motherfuckers can code from their brains or if they're googling it as well sometimes#personal
0 notes
sho-snippets · 11 months
Text
keywordでフィルター
完全一致
filteredBots = bots.value.filter((bot) => bot.title.includes(searchQuery.value) )
大文字小文字無視(toLowerCaseにそろえてからfilter)
filteredBots = bots.value.filter((bot) => bot.title.toLowerCase().includes(searchQuery.value.toLowerCase()) )
0 notes
htmlcodegenerator · 3 months
Text
Tumblr media
How to Check for Duplicate Names in an Array Online
0 notes
newcodesociety · 11 months
Text
1 note · View note
mmainulhasan · 1 year
Text
🛠️ JavaScript Tip of the Day 🛠️
Ever encountered an array with duplicate values? Use Set to get rid of it quickly!
Tumblr media
Elegantly remove duplicates with just one line! 🚀
1 note · View note
danielwrobert · 1 year
Text
Working With JavaScript Arrays: Static Methods
In JavaScript, arrays are one of the most commonly used data structures. They are a collection of elements, each with a unique index or key. JavaScript offers a variety of methods to work with arrays that make it easy to manipulate and transform your data. This short series will list out some of the most commonly used array methods, grouped into three classifications (destructive,…
Tumblr media
View On WordPress
0 notes
justnshalom · 1 year
Text
JavaScript: Find Intersection
JavaScript: Find Intersection In JavaScript, finding the intersection of two arrays is a common programming task. The intersection is the set of elements that are present in both arrays. There are several ways to accomplish this in JavaScript, depending on the specific requirements and constraints of your project. Method 1: Using a loop One of the simplest approaches to find the intersection is…
View On WordPress
0 notes